Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换为原始字符串文字?_Python_Python 3.x - Fatal编程技术网

Python 替换为原始字符串文字?

Python 替换为原始字符串文字?,python,python-3.x,Python,Python 3.x,如果我有一根绳子 s = 'this is a \n tennis ball' 如果在python中执行: s.replace("\n", "nice") 输出为: "this is a nice tennis ball" 另一方面,如果我用python执行 s.replace(r"\n","nice"), 输出是 "this is a \n tennis ball" 使用简单的普通字符串和使用原始字符串有什么区别?这些不同输出的原因是什么 一个“r”字符串文字使'\'字符代表一个实

如果我有一根绳子

s = 'this is a \n tennis ball'
如果在python中执行:

s.replace("\n", "nice")
输出为:

"this is a nice tennis ball"
另一方面,如果我用python执行

s.replace(r"\n","nice"), 
输出是

"this is a \n tennis ball"

使用简单的普通字符串和使用原始字符串有什么区别?这些不同输出的原因是什么

一个“r”字符串文字使
'\'
字符代表一个实际的
'\'
字符,而不是一个特殊字符,它的行为就像一个原始字符串

在字符串
s='这是一个网球'
中,如果您添加了一个'r',那么它的
s=r'这是一个网球'
它将把'\'符号识别为一个普通的原始'\'符号,并在使用
s.replace()时使用
r'\'
来识别它


我的解释可能不太清楚,我建议阅读

的答案,注意这与
str.replace()
无关。您应该仔细查看不同的值
'\n'
r'\n'
product。