mix*_*mix 31 python string replace
在python中给出一个字符串,例如:
s = 'This sentence has some "quotes" in it\n'
Run Code Online (Sandbox Code Playgroud)
我想用任何引号转义创建该字符串的新副本(以便在Javascript中进一步使用).所以,例如,我想要的是产生这个:
'This sentence has some \"quotes\" in it\n'
Run Code Online (Sandbox Code Playgroud)
我试过用过replace(),比如:
s.replace('"', '\"')
Run Code Online (Sandbox Code Playgroud)
但是返回相同的字符串.那么我试过这个:
s.replace('"', '\\"')
Run Code Online (Sandbox Code Playgroud)
但是返回双重转义的引号,例如:
'This sentence has some \\"quotes\\" in it.\n'
Run Code Online (Sandbox Code Playgroud)
如何更换"使用\"?
更新:
我需要作为此可复制文本的输出,将引号和换行显示为已转义.换句话说,我希望能够复制:
'This sentence has some \"quotes\" in it.\n'
Run Code Online (Sandbox Code Playgroud)
如果我使用原始字符串和print结果,我得到正确的转义引号,但转义的换行符不会打印.如果我不使用print那么我得到我的新行,但双重转义引号.如何创建一个我可以复制的字符串,显示换行和报价转义?
Yus*_*f S 34
嗨,通常在使用Javascript时,我使用Python提供的json模块.它会像user2357112指出的那样逃避字符串以及其他一些东西.
import json
string = 'This sentence has some "quotes" in it\n'
json.dumps(string) #gives you '"This sentence has some \\"quotes\\" in it\\n"'
Run Code Online (Sandbox Code Playgroud)
Tim*_*ers 22
你的第二次尝试是正确的,但是你会对字符串repr和str字符串之间的区别感到困惑.第二种方式的更惯用的方法是使用"原始字符串":
>>> s = 'This sentence has some "quotes" in it\n'
>>> print s
This sentence has some "quotes" in it
>>> print s.replace('"', r'\"') # raw string used here
This sentence has some \"quotes\" in it
>>> s.replace('"', r'\"')
'This sentence has some \\"quotes\\" in it\n'
Run Code Online (Sandbox Code Playgroud)
原始字符串是WYSIWYG:原始字符串中的反斜杠只是另一个字符.这是 - 正如你所发现的那样 - 容易让人感到困惑;-)
打印字符串(上面的倒数第二个输出)表明它包含您现在想要的字符.
如果没有print(上面的最后一个输出),Python会repr()在显示之前隐式应用该值.结果是一个字符串,如果Python要评估它,它将产生原始字符串.这就是为什么反叛在最后一行加倍.它们不在字符串中,但是需要这样,如果Python要对它进行评估,每个都\\将成为\结果中的一个.
您的最后一次尝试按预期工作.您看到的双反斜杠只是显示实际位于字符串中的单个反斜杠的一种方式.您可以通过检查结果的长度来验证这一点len().
有关双反斜杠的详细信息,请参阅: __repr__()
更新:
在回答您编辑的问题时,其中一个问题怎么样?
print repr(s).replace('"', '\\"')
print s.encode('string-escape').replace('"', '\\"')
Run Code Online (Sandbox Code Playgroud)
或者对于python 3:
print(s.encode('unicode-escape').replace(b'"', b'\\"'))
Run Code Online (Sandbox Code Playgroud)