Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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_Regex - Fatal编程技术网

在Python中更新字符串中字符的最快方法

在Python中更新字符串中字符的最快方法,python,regex,Python,Regex,我必须用字符串中的“%”替换每个“%”字符,因为字符串是不可变的,所以我正在执行list(string),然后用“%”替换每个“%”。 但是字符串可能是巨大的(len(string)>2000),因此列表可能是巨大的,可能会减慢速度,所以我想知道在Python2.7中实现这一点的最快方法,为什么不对字符串使用replace方法呢? 使用以下代码 a = "hello %" print(a.replace("%","%%") 还有一种方法,那就是使用正则表达式。但是,要了解为什么字符串替换方法优

我必须用字符串中的“%”替换每个“%”字符,因为字符串是不可变的,所以我正在执行
list(string)
,然后用“%”替换每个“%”。
但是字符串可能是巨大的(len(string)>2000),因此列表可能是巨大的,可能会减慢速度,所以我想知道在Python2.7中实现这一点的最快方法,为什么不对字符串使用replace方法呢? 使用以下代码

a = "hello %"
print(a.replace("%","%%")

还有一种方法,那就是使用正则表达式。但是,要了解为什么字符串替换方法优于正则表达式

use
some_var.replace(“%”,“%%”)
FunctionString在Python中是不可变的。您的最佳选择是
。替换