如何避免在python中从文本文件读取unicode字符串时出现换行符

如何避免在python中从文本文件读取unicode字符串时出现换行符,python,unicode,decode,encode,Python,Unicode,Decode,Encode,如何从使用python从文本文件读取的unicode文本中删除换行符,即“\n”?另外,如何测试列表的值是否为unicode字符串中的换行符?要从文本文件中删除换行符,可以使用rstrip() # 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 linebre

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

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

# 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]
要测试值是否为换行符,请执行以下操作:

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())

Unicode字符串与标准字符串具有相同的方法,您可以用行删除“\n”。替换(r“\n”和“”)并检查它在unc中是否存在,用“\n”表示

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