当打印包含反斜杠的字符串时,我希望反斜杠 ( \) 保持不变。
test1 = "This is a \ test String?"
print(test1)
'This is a \\ test String?'
test2 = "This is a '\' test String?"
print(test2)
"This is a '' test String?"
Run Code Online (Sandbox Code Playgroud)
我期望的分别是“ This is a \ test String!”或“ This is a '\' test String!”。我怎样才能做到这一点?
两个问题。
第一种情况,您得到的是表示形式而不是字符串值。这是一个经典的解释,例如:Python prints Two backslashrather not one
第二种情况,你不情愿地逃避引用。在所有情况下都使用原始字符串前缀(对于 Windows 硬编码路径尤其危险,其中\test变为<TAB>est):
test2 = r"This is a '\' test String?"
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,它“有效”,因为\ 不会转义任何内容(有关转义序列的完整列表,请检查此处),但在一般情况下我不会太依赖它。这个原始前缀也没有什么坏处:
test1 = r"This is a \ test String?"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |