0

The following code does what I want:

if myString.startswith(", "):
    myString = myString.lstrip(", ")
if myString.endswith(", "):
    myString = myString.rstrip(", ")
if re.search(", ,", myString):
   myString = re.sub(", ,", "", myString)

Basically, I want it to remove any leading commas, trailing commas, and anywhere two commas appear without anything in between them. This does the trick, but I am betting there is a way to simplify this to make it more elegant and use fewer lines of code.

Any suggestions would really be appreciated. Thanks in advance!

1
  • 1
    Fewer lines of code != simplification. Why not just always run lstrip, rstrip and re.sub, if it can't find any matches it will return the un-altered string Commented Aug 27, 2013 at 7:33

5 Answers 5

8

For a starter, I'd use .strip, which has both rstrip and lstrip. And then, replace for the two commas:

MyString = MyString.strip(", ").replace(", , ", "")
Sign up to request clarification or add additional context in comments.

Comments

2

Using split + join:

>>> s = ', a, b, ,c, '
>>> ', '.join(x for x in map(str.strip, s.split(',')) if x)
'a, b, c'

Comments

1

You could use re.sub:

import re
myString = re.sub('^, |, $|, ,', '', myString)

Comments

1

The code from the answers compared with timeit:

s = ", 1, 2, , 3, 4, , 5, 6, , 7, 8, , 9, 10, , 11, 12, , 13, 14, , 15, 16 ,"

def f1(s):
    s = s.strip(", ").replace(", , ", "")

def f2(s):
    s = ', '.join(x for x in map(str.strip, s.split(',')) if x)

def f3(s):
    s = re.sub('^, |, $|, ,', '', s)

if __name__ == '__main__':
    import timeit, re

    print(timeit.timeit("f1(s)", setup="from __main__ import f1, s"))
    print(timeit.timeit("f2(s)", setup="from __main__ import f2, s"))
    print(timeit.timeit("f3(s)", setup="from __main__ import f3, s"))

Results (on my netbook):

1.44931602478
13.0764448643
11.3456158638

Comments

0

You probably want that , , replaced by , instead of nothing.

>>> " ,a,b,,c, ".strip(' ,').replace(',,', ',')
'a,b,c'

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.