令我惊讶的是,这么简单的事情却困扰着我。下面是代码
list = []
f = open("log.txt", "rb") # log.txt file has line separated values,
for i in f.readlines():
for value in i.split(" "):
list.append(value)
print list
输出是
['xx00', '\n', 'xx01in', '\n', 'xx01na', '\n', 'xx01oz', '\n', 'xx01uk', '\n']
我怎样才能摆脱新行,即“\n”?
最佳答案
list = []
f = open("log.txt", "rb") # log.txt file has line separated values,
for i in f.readlines():
for value in i.strip().split(" "):
list.append(value)
print list
.strip()
删除尾随的换行符。明确地说,您可以在某些情况下使用 .strip('\n')
或 .strip('\r\n')
。
你可以阅读更多关于 .strip()
here
编辑
做你想做的事的更好方法:
with open("log.txt", 'rb') as f:
mylist = [val for subl in [l.split(' ') for l in f.read().splitlines()] for val in subl]
对于看起来更容易的答案,您可以导入 itertools 并使用 chain 来展平列表列表,例如@ Jon Clements example
所以它看起来像这样:
from itertools import chain
with open("log.txt", 'rb') as f:
mylist = list(chain.from_iterable(l.split(' ') for l in f.read().splitlines()))
关于转换为列表时,python 行分隔文本中的值,将 "\n"添加到列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12950959/