Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 当我使用name.replace(';N';,';N';)而不是name.replace(";N";)时,为什么会收到错误_Python_Python 3.x_String - Fatal编程技术网

Python 当我使用name.replace(';N';,';N';)而不是name.replace(";N";)时,为什么会收到错误

Python 当我使用name.replace(';N';,';N';)而不是name.replace(";N";)时,为什么会收到错误,python,python-3.x,string,Python,Python 3.x,String,以下代码块引发错误: greeting = 'Hello' name = 'Nisarg' message = f'{greeting}, {name.replace('N','n')}. Welcome!' print(message) 但是,下面的代码块似乎工作得很好: greeting = 'Hello' name = 'Nisarg' message = f'{greeting}, {name.replace("N","n")}. Welcome!' print(message

以下代码块引发错误:

greeting = 'Hello'
name = 'Nisarg'

message = f'{greeting}, {name.replace('N','n')}. Welcome!'

print(message)
但是,下面的代码块似乎工作得很好:

greeting = 'Hello'
name = 'Nisarg'

message = f'{greeting}, {name.replace("N","n")}. Welcome!'

print(message)

在Python中,单引号和双引号可以相互替换,但是,为什么这里会出现问题呢

SO突出显示应该会给你一个线索。单引号和双引号确实是可替换的,但是您已经在整个字符串周围使用单引号了;因此,当Python遇到另一个单引号时,它将其解释为表示您正在结束字符串


这正是为什么首先有多种引用字符串的方法。

因为您试图在由单引号删除的字符串中包含单引号。字符串中的第一个单引号以字符串文字结尾。如果您执行了
f“{greeting},{name.replace('N','N')}。欢迎!”
。这不会是个问题。你没有正确使用引号