我有一个字符串列表,比如

当前函数

def sub(old: string, new: string, words: list):
    words[:] = [w.replace(old, new) for w in words]

如果输入为old='I'

current output = ['TwASDnkle TwASDnkle', 'How ASD wonder']

intended output = ['Twinkle Twinkle', 'How ASD wonder']

这是我在这里的第一篇帖子,我学习python才几个月,所以我非常感谢您的帮助,谢谢

推荐答案

不要在循环中使用str.replace.这通常不会达到预期效果,因为它不适用于单词,但适用于所有匹配项.

取而代之的是,split个单词,替换为match和join:

l = ['Twinkle Twinkle', 'How I wonder']

def sub(old: str, new: str, words: list):
    words[:] = [' '.join(new if w==old else w for w in x.split()) for x in words]
    
sub('I', 'ASD', l)

yields :['Twinkle Twinkle', 'How ASD wonder']

或者使用带有单词边界的正则表达式:

import re

def sub(old, new, words):
    words[:] = [re.sub(fr'\b{re.escape(old)}\b', new, w) for w in words]
    
l = ['Twinkle Twinkle', 'How I wonder']
sub('I', 'ASD', l)
# ['Twinkle Twinkle', 'How ASD wonder']

NB. As @re-za pointed out, it might be a better practice to 100 a new list rather than mutating the input, just be aware of it

Python相关问答推荐

从收件箱获取特定列中的重复行

Flask:如何在完整路由代码执行之前返回验证

如何在telegram 机器人中发送音频?

创建带有二维码的Flask应用程序,可重定向到特定端点

如何从具有多个嵌入选项卡的网页中Web抓取td类元素

比较两个数据帧并并排附加结果(获取性能警告)

在Python中处理大量CSV文件中的数据

基于字符串匹配条件合并两个帧

两个pandas的平均值按元素的结果串接元素.为什么?

UNIQUE约束失败:customuser. username

Python列表不会在条件while循环中正确随机化'

使用Python和文件进行模糊输出

使用特定值作为引用替换数据框行上的值

将scipy. sparse矩阵直接保存为常规txt文件

在单次扫描中创建列表

Maya Python脚本将纹理应用于所有对象,而不是选定对象

如何创建引用列表并分配值的Systemrame列

如何获取Python synsets列表的第一个内容?

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

Pandas:填充行并删除重复项,但保留不同的值