Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.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/0/asp.net-core/3.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 - Fatal编程技术网

在Python中更改字符串中的字母

在Python中更改字符串中的字母,python,Python,我正在研究python的一些基础知识,但不知怎么的,我并没有让这些东西正常工作 string = 'water' string.replace('a','u') print(string) 我想把这个脚本打印出来。然而,即使使用了字符串,它仍然可以打印出水。我做错了什么 string.replace('a','u') 不改变字符串。它返回一个新字符串,您将在案例中丢弃该字符串。试一试 string = string.replace('a','u') 相反。您可以使用Regex模块替换来

我正在研究python的一些基础知识,但不知怎么的,我并没有让这些东西正常工作

string = 'water'

string.replace('a','u')

print(string)
我想把这个脚本打印出来。然而,即使使用了字符串,它仍然可以打印出水。我做错了什么

string.replace('a','u')
不改变字符串。它返回一个新字符串,您将在案例中丢弃该字符串。试一试

string = string.replace('a','u')

相反。

您可以使用Regex模块替换来完成它

import re
my_string = 'water'
my_string2 = re.sub('a', 'u', my_string)
print(my_string2)

字符串是不可变的。replace是Python编程语言中的一个内置函数,它返回字符串的一个副本,以补充前面的注释,我建议阅读这个古老但有用的SO问题,它澄清了不可变的含义:同时键入helpstring.replace,它告诉您返回一个S的副本,其中所有出现的子字符串old都被new替换。在这种情况下真的不需要使用re模块吗?它真的改变了什么吗?在结果方面,不,但我认为在一个不好的正则表达式的情况下用正则表达式来回答是个坏主意。因为正则表达式可能是一个性能问题。那么简短的回答是:不,在这种情况下,冗长的回答是:是