【问题标题】:Is there a way to remove "\n" in a list [duplicate]有没有办法删除列表中的“\n”[重复]
【发布时间】:2020-02-29 12:58:45
【问题描述】:

我有一个保存在 .txt 文件中的各种目录的列表,我使用 file.readlines() 将该 .txt 文件中的所有行放入一个列表中。

有没有办法可以过滤掉每个条目末尾的“\n”?

这个 .txt 文件夹中的一行看起来像这样

D:/Music/Song.mp3\n

我基本上是从 .txt 文件中获取条目并将它们放入 Tkinter ListBox,以便用户可以从该 ListBox 中选择他们的歌曲。

【问题讨论】:

标签: python directory


【解决方案1】:

使用.replace()方法

string_list = [
    "D:/Music/Song.mp3\n",
    "hello world\n"
]

new_string_list = [string.replace("\n","") for string in string_list]

【讨论】:

    【解决方案2】:

    最简单的方法是使用.read().splitlines() 而不是.readlines()

    【讨论】:

      【解决方案3】:

      您可以使用 python 的内置 strip 函数,该函数删除前导空格。比如你读入文件后:

      txtinput = D:/Music/Song.mp3\n
      txtinput = txtinput.strip() # This returns the required file path without the trailing new line
      

      同样,您可以查看How to remove \n from a list element? 了解更多信息

      有关条带功能的更多信息: https://www.programiz.com/python-programming/methods/string/strip

      【讨论】:

        【解决方案4】:

        做:

        for line in file:
            directory = line.strip()
        

        而不是使用readline() 方法。

        使用.strip() 可以得到没有\n 的线路

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-28
          相关资源
          最近更新 更多