【问题标题】:how to avoid linebreakers from unicode string read from text file in python如何避免从python中的文本文件读取的unicode字符串中的换行符
【发布时间】:2013-08-05 23:48:51
【问题描述】:

如何从使用 python 从文本文件读取的 unicode 文本中删除换行符,即“\n”?另外,如何测试列表的值是否在 unicode 字符串中是换行符?

【问题讨论】:

    标签: python unicode decode encode


    【解决方案1】:
    # Checks if the text is more than 0 symbols. And if the last symbol is "\n"
    if len(test) > 0 and test[-1:]=="\n":
        # If so, remove the last linebreak
        test = test[0:-1]
    

    【讨论】:

      【解决方案2】:

      要从文本文件中删除换行符,您可以使用 rstrip():

      with open('somefile.txt', 'r') as f:
           for line in f:
               print(line.rstrip())
      

      测试一个值是否是换行符:

      for item in some_values:
          if item == '\n':
              do something
      

      或者,您可以测试 '\n' 是否在一行中:

      with open('somefile.txt', 'r') as f:
           for line in f:
                 if '\n' in line:
                      print(line.rstrip())
      

      【讨论】:

        【解决方案3】:

        Unicode 字符串与标准字符串有相同的方法,可以用 line.replace(r'\n','') 去掉 '\n' 并在 unc 中用 '\n' 检查是否存在

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-22
          • 2021-01-19
          • 1970-01-01
          • 1970-01-01
          • 2023-03-20
          • 2019-03-18
          相关资源
          最近更新 更多