我需要在python中使用一个小函数来读取文件,然后将所有字符删除到AND INCLUDING一个逗号字符。例如,以下两个行文件:
hello,my name is
john,john, mary
将是:
my name is
john, mary
答案 0 :(得分:5)
建议您使用re.split()
;但是,split()
的常规str
方法也应该足够了:
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)
答案 1 :(得分:2)
您想要的是Regular Expressions。具体来说,split应该运作良好。
瓦尔斯= re.split( '',串,1)
答案 2 :(得分:1)
也:
line = 'hello,my name is'
line[line.find(',')+1 : ] #find position of first ',' and slice from there
>>> 'my name is'
答案 3 :(得分:1)
>>> 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]
''