我有一个清单:
Cat
Dog
Monkey
Pig
我有一个脚本:
import sys
input_file = open('list.txt', 'r')
for line in input_file:
sys.stdout.write('"' + line + '",')
输出结果为:
"Cat
","Dog
","Monkey
","Pig",
我想:
"Cat","Dog","Monkey","Pig",
我无法摆脱处理列表中的行所发生的回车。在最后摆脱的奖励点。不知道如何查找和删除最后一个实例。
答案 0 :(得分:18)
str.rstrip或简称str.strip是从文件读取的数据中拆分回车符(换行符)的正确工具。注意str.strip将从任一端剥去空白。如果您只对剥离换行感兴趣,请使用strip('\n')
更改行
sys.stdout.write('"' + line + '",')
到
sys.stdout.write('"' + line.strip() + '",')
请注意,在您的情况下,一个更简单的解决方案就是
>>> from itertools import imap
>>> with open("list.txt") as fin:
print ','.join(imap(str.strip, fin))
Cat,Dog,Monkey,Pig
或仅使用List COmprehension
>>> with open("test.txt") as fin:
print ','.join(e.strip('\n') for e in fin)
Cat,Dog,Monkey,Pig
答案 1 :(得分:8)
您可以使用.rstrip()
从字符串的右侧删除换行符:
line.rstrip('\n')
或者您可以告诉它删除所有空格(包括空格,制表符和回车):
line.rstrip()
这是.strip()
method的一个更具体的版本,可以从字符串的两个边删除空格或特定字符。
对于特定的案例,您可以坚持使用简单的.strip()
,但对于您只想删除 换行符的一般情况,我&#39 ; d坚持使用`.rstrip(' \ n')。
我使用不同的方法编写字符串:
with open('list.txt') as input_file:
print ','.join(['"{}"'.format(line.rstrip('\n')) for line in input_file])
使用','.join()
可以避免使用最后一个逗号,并且使用str.format()
method比使用字符串连接更容易(更不用说更快了)。
答案 2 :(得分:1)
首先,为了使它全部显示在一行上,你应该得到'\n'
的外皮。我发现line.rstrip('\n')
可以很好地工作。
为了摆脱','最后我会将所有单词放在列表中添加引号。然后使用join(),使用“,”
连接列表中的所有单词temp = []
for line in file:
i = line.rstrip('\n')
word = '"'+i+'"'
temp.append(word)
print ",".join(temp)
那应该得到所需的输出