相关疑难解决方法(0)

在Python中处理字符串中的转义序列

有时当我从文件或用户那里获得输入时,我会得到一个包含转义序列的字符串.我想以与Python处理字符串文字中的转义序列相同的方式处理转义序列.

例如,假设myString定义为:

>>> myString = "spam\\neggs"
>>> print(myString)
spam\neggs
Run Code Online (Sandbox Code Playgroud)

我想要一个函数(我会称之为process)这样做:

>>> print(process(myString))
spam
eggs
Run Code Online (Sandbox Code Playgroud)

重要的是该函数可以处理Python中的所有转义序列(在上面链接的表中列出).

Python有功能吗?

python string escaping

93
推荐指数
4
解决办法
8万
查看次数

我如何在Python3中使用.decode('string-escape')?

我有一些需要转义的转义字符串.我想用Python做这件事.

例如,在python2.7中,我可以这样做:

>>> "\\123omething special".decode('string-escape')
'Something special'
>>> 
Run Code Online (Sandbox Code Playgroud)

我如何在Python3中完成它?这不起作用:

>>> b"\\123omething special".decode('string-escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: unknown encoding: string-escape
>>> 
Run Code Online (Sandbox Code Playgroud)

我的目标是成为一个像这样的字符串:

s\000u\000p\000p\000o\000r\000t\000@\000p\000s\000i\000l\000o\000c\000.\000c\000o\000m\000
Run Code Online (Sandbox Code Playgroud)

把它变成:

"support@psiloc.com"
Run Code Online (Sandbox Code Playgroud)

在进行转换之后,我将探测我的字符串是用UTF-8还是UTF-16编码的.

python escaping python-3.x

49
推荐指数
4
解决办法
4万
查看次数

在python中转换字符串,如\\ uXXXX

我有一个像\ uXXXX(表示)的字符串,我需要将其转换为unicode.我从第三方服务收到它,因此python解释器不转换它,我需要在我的代码中进行转换.我怎么用Python做的?

>>> s
u'\\u0e4f\\u032f\\u0361\\u0e4f'
Run Code Online (Sandbox Code Playgroud)

python unicode

17
推荐指数
2
解决办法
6496
查看次数

python3 unicode-escape不能用于非ascii字节?

在python2中,有string-escapeunicode-escape.对于utf-8字节字符串,string-escape可以转义\并保留非ascii字节,如:

"??\\n".decode('string-escape')
'\xe4\xbd\xa0\xe5\xa5\xbd\n'
Run Code Online (Sandbox Code Playgroud)

但是,在python3中,string-escape被删除.我们必须将字符串编码为字节并使用以下方法解码unicode-escape:

"This\\n".encode('utf_8').decode('unicode_escape')
'This\n'
Run Code Online (Sandbox Code Playgroud)

它适用于ascii字节.但是非ascii字节也将被转义:

"??\\n".encode('utf_8')
b'\xe4\xbd\xa0\xe5\xa5\xbd\\n'
"??\\n".encode('utf_8').decode('unicode_escape').encode('utf_8')
b'\xc3\xa4\xc2\xbd\xc2\xa0\xc3\xa5\xc2\xa5\xc2\xbd\n'
Run Code Online (Sandbox Code Playgroud)

所有非ascii字节都被转义,这会导致编码错误.

那么有解决方案吗?在python3中是否可以保留所有非ascii字节并解码所有转义字符?

python python-3.x

11
推荐指数
1
解决办法
3013
查看次数

用真实的\ n输出替换其中带有\ n的文本

我正在尝试从杜松路由器获取配置,但是我遇到以下问题:

设置后

stdin, stdout, stderr = client1.exec_command('show configuration interfaces %s' % SID)
 CONFIG = stdout.read()
 print CONFIG
Run Code Online (Sandbox Code Playgroud)

它带给我像这样的东西

'description El_otro_Puerto_de_la_Routing-instance;\nvlan-id 309;\nfamily inet {\n    mtu 1600;\n    address 10.100.10.10/24;\n}\n'
Run Code Online (Sandbox Code Playgroud)

问题是我想以这种格式接收该信息:

'description El_otro_Puerto_de_la_Routing-instance;
 nvlan-id 309;
 nfamily inet {
  mtu 1600;
  address 10.100.10.10/24;
 }
Run Code Online (Sandbox Code Playgroud)

因此,我希望\ n实际上是换行符,而不仅仅是显示“ \ n”字符串。

python blank-line juniper

4
推荐指数
2
解决办法
8214
查看次数

标签 统计

python ×5

escaping ×2

python-3.x ×2

blank-line ×1

juniper ×1

string ×1

unicode ×1