gpt4 book ai didi

python - 如何在索引时忽略\n

转载 作者:行者123 更新时间:2023-12-01 02:06:03 25 4
gpt4 key购买 nike

我得到了一个包含以下文本的文件:

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

我要做的是创建另一个文件并重写此文本,但是:如果一个字符串以元音结尾,那么我必须在该字符串后面加上“way”如果字符串以辅音结尾,我必须重写最后一个字母并添加“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”。在其他字符串中 line[-1] ==\n 我的问题是如何忽略它并检查最后一个字母。

最佳答案

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,然后将换行符添加回末尾。

关于python - 如何在索引时忽略\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com