【问题标题】:How to change a string in list of strings in python如何在python中更改字符串列表中的字符串
【发布时间】:2019-06-29 08:38:52
【问题描述】:

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

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

【问题讨论】:

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


【解决方案1】:

Python 中的变量不能用作指针,请参阅this SO question 以获得更好的解释。 在您的第一段代码中,您正在更改变量 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???" :)

【讨论】:

    【解决方案2】:

    您的第一个代码不起作用,因为它只为局部变量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())
    

    【讨论】:

      【解决方案3】:

      如果您想删除前导逗号,那么 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 2013-12-07
        • 1970-01-01
        • 2020-03-12
        • 2010-12-18
        • 1970-01-01
        • 2015-07-18
        相关资源
        最近更新 更多