Python 替换字符串列表中的整个字符串

Python 替换字符串列表中的整个字符串,python,string,python-3.x,replace,Python,String,Python 3.x,Replace,我有一张代币清单。有些以@符号开头。我想将所有这些字符串更改为通用的@user。我试过这个: >>> words = ['@john', 'nina', 'michael', '@bebeto'] >>> words = [w.replace(w, '@user') for w in words if w.startswith('@')] >>> words ['@user', '@user'] >>> 我这里出了什么问

我有一张代币清单。有些以
@
符号开头。我想将所有这些字符串更改为通用的
@user
。我试过这个:

>>> words = ['@john', 'nina', 'michael', '@bebeto']
>>> words = [w.replace(w, '@user') for w in words if w.startswith('@')]
>>> words
['@user', '@user']
>>> 

我这里出了什么问题?

您的列表理解导致了不需要的输出,请更改

[w.replace(w, '@user') for w in words if w.startswith('@')]


您的列表理解导致了不希望的输出,请更改

[w.replace(w, '@user') for w in words if w.startswith('@')]

您可以尝试以下方法:

words = ['@john', 'nina', 'michael', '@bebeto']
new_words = ['@user' if i.startswith('@') else i for i in words]
输出:

['@user', 'nina', 'michael', '@user']
您可以尝试以下方法:

words = ['@john', 'nina', 'michael', '@bebeto']
new_words = ['@user' if i.startswith('@') else i for i in words]
输出:

['@user', 'nina', 'michael', '@user']

首先,你可以简化列表的第一部分。这是等效的,不做不必要的替换:

words = ['@user' for w in words if w.startswith('@')]
在列表理解中,末尾的if子句决定是否包含内容。所以if基本上说,只保留以@开头的元素。但你想保留所有元素

相反,您可以使用条件表达式来决定是获取“@user”还是原始单词:

words = ['@user' if w.startswith('@') else w for w in words]

首先,你可以简化列表的第一部分。这是等效的,不做不必要的替换:

words = ['@user' for w in words if w.startswith('@')]
在列表理解中,末尾的if子句决定是否包含内容。所以if基本上说,只保留以@开头的元素。但你想保留所有元素

相反,您可以使用条件表达式来决定是获取“@user”还是原始单词:

words = ['@user' if w.startswith('@') else w for w in words]

你想要的输出是什么?@Ajax1234我想
['@user',nina',michael','@user']
你想要的输出是什么?@Ajax1234我想
['@user',nina',michael','.@user']
在Python中这是无效的语法。有关正确的解决方案,请参阅其他答案。这在Python中是无效的语法。有关正确的解决方案,请参阅其他答案。