我收到了一个包含以下文字的文件:
with open("file1.txt", "w") as file1:
file1.write("Thou blind fool, Love, what dost thou to mine eyes\n"
"That they behold, and see not what they see\n"
"They know what beauty is, see where it lies\n"
"Yet what the best is take the worst to be")
我要做的是创建另一个文件并重写此文本但是: 如果一个字符串以元音结尾而不是我必须放置"方式"在此字符串之后 如果一个字符串以辅音结尾,我必须重写最后一个字母并添加" ay"它。
我的代码是:
def change_str():
with open("file1.txt", "r") as file1, open("file2.txt", "w") as file2:
lines = file1.readlines()
for line in lines:
if line[-1] in "aiueoy":
file2.write(line + " " + "way")
else:
file2.write(line + " " + line[-1] + "ay")
因此它只有1条正确的输出线。它是最后一个,因为它没有" / n"。在其他字符串行[-1] == \ n,我的问题是如何忽略它并检查最后一个字母。
答案 0 :(得分:2)
with open("file1.txt", 'r') as file1, open("file2.txt", 'w') as file2:
lines = file1.readlines()
for line in lines:
if line.strip()[-1] in 'aeiouy':
file2.write(line.strip() + " " + "way" + '\n')
else:
file2.write(line.strip()[:-1] + "ay" + '\n')
这样的事情怎么样?使用strip然后将换行符添加到最后。
答案 1 :(得分:0)
您可以使用:
而不是readlinesfile1.read().splitlines()
这样你就不必从字符串中删除任何结束字符。