[英]How to change a string in list of strings in python
我正在尝试删除句子中的主要昏迷,但我不知道为什么这不起作用
text = ",greetings friends"
text_l = text.split()
for word in text_l:
if word.startswith(','):
word = word[1:]
text = ' '.join(text_l)
>>> ,greetings friends
但是确实如此。
text = ",greetings friends"
text_l = text.split()
for word in text_l:
if word.startswith(','):
indw = text_l.index(word)
text_l[indw] = word[1:]
text = ' '.join(text_l)
>>> greetings friends
您的第一个代码不起作用,因为它仅将新值分配给局部变量word
, 而没有:更改列表中的字符串。 您的第二个代码有效(如您所注意到的),但是效率很低,因为您必须找到要删除的每个单词的index
。 相反,您可以使用enumerate
同时迭代单词和索引,也可以使用lstrip
而不是对字符串进行切片。
text_l = text.split()
for i, word in enumerate(text_l):
if word.startswith(','):
text_l[i] = word.lstrip(",")
text = ' '.join(text_l)
另外,当使用lstrip
, if
不再需要if
了,我们可以将整个内容压缩为' '.join(...)
的单行生成器表达式:
text = ' '.join(word.lstrip(",") for word in text.split())
Python中的变量不能用作指针,请参见此SO问题以获取更好的解释。 在代码的第一部分中,您将更改变量word
的值,而不是该单词所引用的对象,因此您的循环不会更改单词原始列表中的任何内容。
第二个代码确实更改了原始列表。
作为建议,可以使用一种更Python化的方法来完成所需的操作:
original_text = ",greetings friends"
text = ' '.join(part.lstrip(',') for part in original_text.split())
text = ' '.join(map(lambda part: part.lstrip(','), original_text.split())) # If you want a colleague to ask you "what's that???" :)
如果要删除前导逗号,则lstrip是您所需的命令。
text = ",greetings friends"
text_l = text.split()
text = []
for word in text_l:
if word.startswith(','):
word = word.lstrip(',')
text.append(word)
text = ' '.join(text)
文本输出为:
greetings friends
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.