【发布时间】:2013-08-05 23:48:51
【问题描述】:
如何从使用 python 从文本文件读取的 unicode 文本中删除换行符,即“\n”?另外,如何测试列表的值是否在 unicode 字符串中是换行符?
【问题讨论】:
标签: python unicode decode encode
如何从使用 python 从文本文件读取的 unicode 文本中删除换行符,即“\n”?另外,如何测试列表的值是否在 unicode 字符串中是换行符?
【问题讨论】:
标签: python unicode decode encode
# 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]
【讨论】:
要从文本文件中删除换行符,您可以使用 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())
【讨论】:
Unicode 字符串与标准字符串有相同的方法,可以用 line.replace(r'\n','') 去掉 '\n' 并在 unc 中用 '\n' 检查是否存在
【讨论】: