首页 > 解决方案 > 从非正式字符串表示中获取干净的字符串

问题描述

我无法将字符串拆分为行。我收到一个似乎被定义为的字符串

txt = str(b"line1 \n line2")

正如这里所描述的,它被转换为字符串的非正式表示。

就像我收到一个定义为的脚本

txt = "b'line1 \n line2'"

如何将我的数据转换为

txt = "line1 \n line2"

不做丑陋的事情

txt = txt[2:-1]

编辑:看到标记为重复,但另一个问题似乎不适用:

txt = str(b"line1\nline2")                                                                     
txt.decode('ascii')                                                                            
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-89-0ccdab40ee23> in <module>
----> 1 txt.decode('ascii')

AttributeError: 'str' object has no attribute 'decode'

标签: python-3.x

解决方案


推荐阅读