如何在python中的字符串列表中更改字符串

时间:2019-06-29 08:38:52

标签: python python-3.x loops for-loop

我正在尝试删除句子中的前导昏迷,但我不明白为什么它不起作用

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

3 个答案:

答案 0 :(得分:1)

您的第一个代码不起作用,因为它仅将新值分配给局部变量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不再是必需的,我们可以将整个内容压缩为' '.join(...)中的单行生成器表达式:

text = ' '.join(word.lstrip(",") for word in text.split())

答案 1 :(得分:1)

Python中的变量不能用作指针,请参见this SO question以获得更好的解释。 在代码的第一部分,您将更改变量word的值,而不是单词所引用的对象,因此循环不会更改单词的原始列表中的任何内容。

第二个代码确实更改了原始列表。

建议,一种更蟒蛇的方式来做您需要的事情:

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???" :)

答案 2 :(得分:0)

如果要删除前导逗号,则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
相关问题