python迭代字符串

use*_*957 1 python string file

我正在将"文章"的内容写入文本文件.

源文件:

lol hi
lol hello
lol text
lol test
Run Code Online (Sandbox Code Playgroud)

蟒蛇:

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'
Run Code Online (Sandbox Code Playgroud)

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

this is my saved file
test
the end
Run Code Online (Sandbox Code Playgroud)

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

this is the saved file
hi
hello
test
text
the end
Run Code Online (Sandbox Code Playgroud)

Sim*_*ser 5

您每次都要替换字符串.您需要存储每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'
Run Code Online (Sandbox Code Playgroud)

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

line.replace('lol ', '', 1).lower().rstrip(' ')
Run Code Online (Sandbox Code Playgroud)

rstrip()它只允许剥离空格而不是所有其他形式的空格.


编辑:另一种方法是写:

mystring.append(line.replace('lol ', '').lower().rstrip())
Run Code Online (Sandbox Code Playgroud)

和:

article = 'this is my saved file\n'+'\n'.join(mystring)+'\nthe end'
Run Code Online (Sandbox Code Playgroud)