2

I need a small function in python that would read in a file and then remove all the characters up to AND INCLUDING a comma character. so for instance the following two line file:

hello,my name is
john,john, mary

would be:

my name is
john, mary
0

4 Answers 4

5

You have been advised to use re.split() already; however, regular split() method of str should suffice as well:

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)
2
  • 1
    Regular split is even better than what you're showing here, because you can specify the maximum number of occurrences as the second parameter: new_str = line.split(',', 1)[1]
    – John Y
    Mar 9, 2012 at 21:04
  • @JohnY - You version is not better because it fails when no comma exists. Jun 28, 2013 at 16:54
2

What you want is called Regular Expressions. Specifically, the split should work well.

vals=re.split(',',string,1)

1
  • Not to split hairs (pun very intended), but calling split isn't the same as using a regex. I mean, the language defined by splitting a string on a given character input is regular, sure, but a regex is a specific means of expressing a regular language. You could just as easily have said "What you want is called a DFA", and you'd be just as half-right. Jun 16, 2015 at 23:52
1

also:

line = 'hello,my name is'
line[line.find(',')+1 :  ]     #find position of first ',' and slice from there
>>> 'my name is'
1

Use partition

>>> 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]
''
2
  • 1
    this is abit messy in the case where ',' doesn't exist!
    – vikki
    Mar 9, 2012 at 20:31
  • @vikki: It depends on what the OP means by "remove all characters up to and including a comma". This could be interpreted to mean that lines without any comma should have all their characters removed (which is what this answer does). However, it is good that you pointed out we should be thinking about edge cases, because that is what often bites us in the real world.
    – John Y
    Mar 9, 2012 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.