【问题标题】:python iterating stringspython迭代字符串
【发布时间】:2012-07-13 15:10:53
【问题描述】:

我正在将“文章”的内容写入文本文件。

源文件:

lol hi
lol hello
lol text
lol test

Python:

for line in all_lines:
    if line.startswith('lol '):
        mystring = line.replace('lol ', '').lower().rstrip()

article = 'this is my saved file\n' + mystring + '\nthe end'

这是保存到 txt 文件的内容:

this is my saved file
test
the end

这是我要保存到 txt 文件的内容:

this is the saved file
hi
hello
test
text
the end

【问题讨论】:

    标签: python string file


    【解决方案1】:

    您每次都在替换字符串。您需要存储每个lol 行的结果,然后将它们全部添加到mystring

    mystring = []
    for line in all_lines:
        if line.startswith('lol '):
            mystring.append(line.replace('lol ', '', 1).lower().rstrip() + '\n')
    
    article = 'this is my saved file\n'+''.join(mystring)+'\nthe end'
    

    在上面的代码中,我将mystring 转换为列表,然后使用join 方法将其转换为最后的字符串。请注意,我已经在每一行中添加了一个换行符 (\n),因为您希望该字符出现在输出中(rstrip() 将其删除)。或者,您可以编写:

    line.replace('lol ', '', 1).lower().rstrip(' ')
    

    这让rstrip() 只去除空格,而不是所有其他形式的空格。


    编辑:另一种方法是编写:

    mystring.append(line.replace('lol ', '').lower().rstrip())
    

    和:

    article = 'this is my saved file\n'+'\n'.join(mystring)+'\nthe end'
    

    【讨论】:

    • replace 这里有点危险; replace('lol ','', 1) 将防止无意的第二次替换。
    • @SimeonVisser -- 我删除了我的评论,因为它不正确。但我很高兴你添加了那个替代方案。 (反正我更清楚)。
    • @mgilson:为什么不正确?每行(最后一行除外)都将使用join() 获得\n,最后一行也将从'\nthe end' 获得。当然,也不是平台无关的代码……
    • @SimeonVisser - 你的答案是完全正确的。是我的评论是错误的。 (因此我将其删除)。
    • 你可以用一个生成器做到这一点:'this is my saved file\n' + ''.join(line.replace('lol ', '').lower() for line in all_lines if line.startswith('lol ')) + 'the end'
    【解决方案2】:

    ...或作为单行,

    mystring = ''.join(line[4:].lower() for line in all_lines if line.startswith('lol '))
    

    【讨论】:

      【解决方案3】:

      您可以采用这种不同的方法:

      with open('test.txt') as fin, open('out.txt', 'w') as fout:
          fout.write('this is my saved file\n')
          for line in fin:
              if line.startswith('lol '):
                  fout.write(line.replace('lol ', '').lower())
          fout.write('the end')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-29
        • 2019-07-15
        • 2014-04-21
        • 2015-11-28
        • 2020-06-20
        • 2020-07-23
        • 2014-09-23
        相关资源
        最近更新 更多