python - 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()
被调用时会得到。
解决方案
\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'"
推荐阅读
- flutter - Flutter TextFormField 带有动态后缀图标
- sql-server - 使用 SSMS 将 Azure 数据库备份到 .BAK 文件?
- angular - httpClient oninit 和 ondestroy 方法
- python-3.x - 通过beautifulsoup 将两张单独的图表合并为一张
- javascript - 无法将 Solidity 合约部署到 Rinkeby 网络(无效的 asm.js:stdlib 的无效成员)
- apache-spark - PySpark - 爆炸时访问结构字段名称和值
- python - Python中的逻辑根据数据框中列中的最大值仅返回相似行中的一行
- iis - 除非刷新应用程序池,否则无法验证 AD 用户
- netty - 执行clientRequest时netty抛出“无法将承诺标记为成功”异常
- unity3d - 我是否需要担心调用 Repaint(); 多次?