首页 > 解决方案 > Python自动将一些字符串转换为原始字符串?

问题描述

Python 似乎会自动将字符串(不仅仅是输入)转换为原始字符串。有人可以解释这里发生了什么吗?

Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit 
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '\stest'
>>> s
'\\stest'
# looks like a raw string
>>> print(s)
\stest
>>> s = '\ntest'
>>> s
'\ntest'
# this one doesn't
>>> s = '\n test'
>>> s
'\n test'
>>> s = r'\n test'
>>> s
'\\n test'
>>> print(s)
\n test

标记为重复的问题似乎很有用,但后来我不明白为什么

>>> s = '\n test'
>>> s
'\n test'
>>> repr(s)
"'\\n test'"

被调用时不会得到两个反斜杠,而当repr()被调用时会得到。

标签: pythonstring

解决方案


\n 是一个有效的转义序列并且'\n'是一个长度为 1 的字符串(换行符)。相比之下,\s 是一个无效的转义序列,因此 Python假设您想要的是一个两个字符串:一个反斜杠字符加上一个 s 字符。

>>> len('\s')
2

您在终端输出上看到的只是这种长度为 2 的字符串的通常表示。请注意,创建 Python 在此处返回给您的字符串的正确方法是 withr'\s'或 with '\\s'

>>> r'\s' == '\\s' == '\s'
True

这是一种已弃用的行为。在 Python 的未来版本中,可能是下一个版本,您的代码将出现语法错误。

由于您使用的是 v3.7.1,因此如果您想了解此类已弃用功能的使用情况,可以启用警告:

$ python -Wall
>>> '\s'
<stdin>:1: DeprecationWarning: invalid escape sequence \s
'\\s'

至于您在编辑后的后续问题:

>>> s = '\n test'
>>> s  # this prints the repr(s)
'\n test'
>>> repr(s)  # this prints the repr(repr(s))
"'\\n test'"

推荐阅读