【发布时间】:2012-03-09 19:40:10
【问题描述】:
我需要 python 中的一个小函数,它可以读取文件,然后删除所有字符,包括逗号字符。例如以下两行文件:
hello,my name is
john,john, mary
应该是:
my name is
john, mary
【问题讨论】:
我需要 python 中的一个小函数,它可以读取文件,然后删除所有字符,包括逗号字符。例如以下两行文件:
hello,my name is
john,john, mary
应该是:
my name is
john, mary
【问题讨论】:
已建议您使用re.split();但是,str 的常规 split() 方法也应该足够了:
with open('new_file', 'w') as f_out, open('my_file') as f_in:
for line in f_in:
new_str = ','.join(line.split(',')[1:])
f_out.write(new_str)
【讨论】:
split 甚至比您在此处显示的更好,因为您可以将最大出现次数指定为第二个参数:new_str = line.split(',', 1)[1]
你想要的是Regular Expressions。具体来说,split 应该可以正常工作。
vals=re.split(',',string,1)
【讨论】:
还有:
line = 'hello,my name is'
line[line.find(',')+1 : ] #find position of first ',' and slice from there
>>> 'my name is'
【讨论】:
>>> foo = 'hello, my name is'
>>> foo.partition(',')[2]
' my name is'
>>> foo = 'john, john, mary'
>>> foo.partition(',')[2]
' john, mary'
>>> foo = 'test,'
>>> foo.partition(',')[2]
''
>>> foo = 'bar'
>>> foo.partition(',')[2]
''
【讨论】:
',' 不存在的情况下有点混乱!