>>> r'\'
File "<stdin>", line 1
r'\'
^
SyntaxError: EOL while scanning string literal
>>> r'\\'
'\\\\'
>>> r'\\\'
File "<stdin>", line 1
r'\\\'
^
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)
似乎解析器可以将原始字符串中的反斜杠视为常规字符(不是原始字符串的全部内容吗?),但我可能遗漏了一些明显的东西.TIA!
有没有办法在python中声明一个字符串变量,以便它内部的所有内容都自动转义,或者有它的文字字符值?
我不是要问如何用斜线来逃避引号,这是显而易见的.我要求的是一个通用的方法,使字符串文字中的所有内容,以便我不必手动完成并转义非常大的字符串的所有内容.有人知道解决方案吗?谢谢!
import os
path= os.getcwd()
final= path +'\xulrunner.exe ' + path + '\application.ini'
print final
Run Code Online (Sandbox Code Playgroud)
我想要出局:
c:\ python25\xulrunner.exe c:\ python25\application.ini
我不希望反斜杠作为字符串工作,我的意思是不要让它逃脱或做任何特别的事情.但我得到一个错误
无效\ x转义
我如何使用'\'作为'\'而不是逃避?
我希望它打印出来
this is '(single quote) and "(double quote)
Run Code Online (Sandbox Code Playgroud)
我使用以下(我想在这里使用原始字符串'r')
a=r'this is \'(single quote) and "(double quote)'
Run Code Online (Sandbox Code Playgroud)
但它打印出来
this is \'(single quote) and "(double quote)
Run Code Online (Sandbox Code Playgroud)
在原始字符串中逃避'的正确方法是什么?
f-strings 在与字典一起使用时表现不佳,如这里所述。
这是一个不太好的行为的例子:
d = {'foo': 'bar'}
# Both work as expected
d["foo"]
d['foo']
# This only works when different quotations are used in the inner and outer strings
f'{d["foo"]}'
f"{d['foo']}"
# This doesn't work
f'{d['foo']}'
f"{d["foo"]}"
# The .format() method doesn't care
'{}'.format(d['foo'])
Run Code Online (Sandbox Code Playgroud)
列出的最后两个 f 字符串导致 a SyntaxError: invalid syntax,这'{d['foo']}'是因为字符串被评估为'{d['foo ']}'。
在使用旧.format()方法时,f-strings 的大括号内的所有内容都没有单独评估的根本原因是什么,以这种方式实现 f-strings 的原因可能是什么?
我喜欢 f-strings,但这似乎是支持旧方法的一点。
是否有Python的组件允许我绕过中间引号?在中,您是否可以指定主启动和停止打印调用,以便解释主启动和停止之间的所有内容,无论该元素最初代表什么?
我试图在程序中打印这行有趣的ASCII,这只是由于中间引号弹出而导致错误的行之一:
print" ./'..|'.|| |||||\``````` " '''''''/||||| ||.`|..`\."
^
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)
编辑:在考虑字符串文字的原始解释时,如果三重引号出现在您的行中,您还可以在原始解释中遇到三重引用的退出.
python ×6
string ×6
escaping ×2
backslash ×1
literals ×1
python-2.7 ×1
python-3.x ×1
rawstring ×1
syntax-error ×1