0

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

4

3 回答 3

0

要从文本文件中删除换行符,可以使用 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())
于 2013-08-05T23:55:02.823 回答
0

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

于 2013-08-05T23:55:52.900 回答
0
# 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]
于 2013-08-05T23:53:47.360 回答