Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在索引时忽略\n_Python - Fatal编程技术网

Python 如何在索引时忽略\n

Python 如何在索引时忽略\n,python,Python,我得到了一个包含以下文本的文件: 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 li

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

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")
所以它只有一条正确的输出线。它是最后一个,因为它没有“/n”。在其他字符串中,行[-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,然后将换行符添加回末尾。

可以使用以下命令代替readlines:

file1.read().splitlines()

这样,您就不必从字符串中删除任何结束行字符。

令人困惑的是:您的文本提到您需要替换字符串的结尾。你是说一句话还是一句台词?您的代码显示的是后者,但从您的文本中看不清楚。@Evert:更清楚的是,它更习惯用法,因为它不太可能中断,而且启动速度更快。将所有行读入一个列表意味着您需要与整个文件大小成比例的RAM,并且在读取所有行之前无法处理一行,对于大型输入,这可能需要相当长的时间。逐行读取意味着RAM要求仅与文件中最长的行(大致)成比例,并且只要操作系统返回第一行就可以开始处理。Strip删除前导字符,而不仅仅是尾随字符,它删除所有空白,而不仅仅是换行符。是的,使用
str.rstrip()
。在行尾去掉多余的空格通常不会破坏任何东西。