Python replace()函数未生效求助:作业字符替换需求无法实现
问题分析与解决方案
嘿,我来帮你揪出问题所在!你代码里的核心问题是每次替换都从原始字符串a开始,而不是基于上一次替换后的结果。
举个例子:
- 你第一次执行
newA = a.replace('.', ' '),这时候newA确实是替换掉.后的字符串; - 但紧接着你又执行
newA = a.replace(',', ' ')——这里你用的是原始的a,不是刚才得到的newA,所以之前替换.的结果直接被覆盖了; - 后面的
replace(';', ' ')和replace('\n', ' ')也是一样的逻辑,最后只有最后一次替换(替换\n)生效,但你的原始字符串里根本没有换行符,所以最终newA和原字符串a看起来完全一样。
解决方法有两种,选你喜欢的就行:
方法1:链式调用replace()
因为replace()方法会返回一个新的字符串,所以我们可以把多次替换连起来,每次都在前一次的结果上继续操作:
a = '''It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...''' newA = a.replace('.', ' ').replace(',', ' ').replace(';', ' ').replace('\n', ' ')
这样所有的替换都会依次生效,最终得到你想要的结果。
方法2:用正则表达式一次性替换(更简洁)
如果你要替换的字符比较多,用re.sub()可以一步搞定,效率也更高:
import re a = '''It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...''' newA = re.sub(r'[.,;\n]', ' ', a)
这里的正则表达式[.,;\n]表示匹配括号里的任意一个字符,然后统一替换成空格,一次操作完成所有替换。
另外补充个小知识点:Python里的字符串是不可变对象,所以replace()不会修改原字符串,只会返回一个新的字符串,这也是为什么你需要把每次替换的结果赋值给变量,而且要确保是基于前一次的结果继续操作~
内容的提问来源于stack exchange,提问作者Mish
相关产品推荐
相关产品推荐

