【问题标题】:Removing \n from a list of strings从字符串列表中删除 \n
【发布时间】:2018-01-31 06:38:00
【问题描述】:

使用此代码...

def read_restaurants(file):
    file = open('restaurants_small.txt', 'r')
    contents_list = file.readlines()

    for line in contents_list:
      line.strip('\n')

    print (contents_list)
    file.close()

read_restaurants('restaurants_small.txt')

我得到了这个结果...

['Georgie Porgie\n', '87%\n', '$$$\n', 'Canadian,Pub Food\n', '\n', 'Queen St. Cafe\n', ' 82%\n', '$\n', '马来西亚,泰文\n', '\n', 'Dumplings R Us\n', '71%\n', '$\n', '中文\n ', '\n', '墨西哥烧烤\n', '85%\n', '$$\n', '墨西哥\n', '\n', '油炸的一切\n', '52% \n', '$\n', '酒吧食品\n']

我想去掉 \n...我在这里阅读了很多我认为可能会有所帮助的答案,但似乎没有什么特别适用于此!

我猜 for...in 进程需要存储为一个新列表,我需要返回它...只是不知道该怎么做!

【问题讨论】:

    标签: python-3.x list


    【解决方案1】:

    更多一点的 Pythonic(在我看来,更容易阅读)的方法:

    def read_restaurants(filename):
        with open(filename) as fh:
            return [line.rstrip() for line in fh]
    

    此外,由于没有人完全澄清这一点:您原来的方法不起作用的原因是 line.strip() 返回了 line 的修改版本,但它没有改变 @ 987654324@:

    >>> line = 'hello there\n'
    >>> print(repr(line))
    'hello there\n'
    >>> line.strip()
    'hello there'
    >>> print(repr(line))
    'hello there\n']
    

    因此,每当您调用stringVar.strip() 时,您都需要对输出进行一些处理 - 像上面那样构建一个列表,或者将其存储在一个变量中,或类似的东西。

    【讨论】:

      【解决方案2】:

      您可以用list comprehension 替换您的常规for 循环,并且您不必将'\n' 作为参数传递,因为strip() 方法默认会删除前导和尾随白色字符:

      contents_list = [line.strip() for line in contents_list] 
      

      【讨论】:

      • 谢谢!我试图输入 \r 以摆脱空白行,但它不起作用......
      • contents_list = [line.strip('\n\r') for line in contents_list]
      • @YogeshRiyat 但正如我已经写过的,您不必将任何内容作为参数传递给line.strip() 来删除空白行,因为这是strip() 删除空白行的默认行为人物。但是,如果您真的坚持要传递参数,那么是的,\n\r 对于 Windows 是正确的。
      • 因此,代码在将 \n 标记到字符串时有效,但对于单独的 '\n' 元素无效。我确实使用了这个过滤器代码,并且它有效。我在其他帖子上看到过,但我真的不知道它是如何工作的!
      • new_contents_list = [line.strip() for line in contents_list] new_contents_list = list(filter(None, new_contents_list))
      【解决方案3】:

      你是对的:你需要一个新的列表。另外,您可能想使用rstrip() 而不是strip()

      def read_restaurants(file_name):
          file = open(file_name, 'r')
          contents_list = file.readlines()
          file.close()
          new_contents_list = [line.rstrip('\n') for line in contents_list]
          return new_contents_list
      

      然后您可以执行以下操作:

      print(read_restaurants('restaurant.list'))
      

      【讨论】:

      • 谢谢!我试图理解为什么函数的参数是 restaurant.list ......你能解释一下吗? read_restaurants(file) 会工作吗?
      • @YogeshRiyat 很好的问题,但只有你能回答它,因为它是你写的!不幸的是,我只是盲目地复制了第一行,直到contents_list = file.readlines()。也就是说,我的代码需要contents_list 并产生new_contents_list
      • @YogeshRiyat 我修改了代码以使其更有意义:现在read_restaurants()file_name(字符串)作为参数;打开该文件,并从该文件中读取所有行。
      猜你喜欢
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2011-04-20
      • 1970-01-01
      相关资源
      最近更新 更多