10

I want to remove all commas from a string using regular expressions, I want letters, periods and numbers to remain just commas

Kev
  • 112,868
  • 50
  • 288
  • 373
jimstandard
  • 937
  • 2
  • 8
  • 16
  • 16
    Come on people, these downvotes are not helpful without an explanation (and they're useless since jim is still at 1 rep). So hi Jim, and welcome to StackOverflow. You can see that many people didn't like your question and downvoted it, probably because it doesn't show much effort on your part. As Ed suggested, you might want to show where exactly you're stuck, and perhaps also explain the context of the problem. The way you've written it now, it doesn't make much sense. You can edit your own question to make it clearer. Also, you might want to read the FAQ (link on top of this page). Cheers! – Tim Pietzcker Sep 09 '11 at 07:22
  • 1
    possible duplicate of [Stripping the single quote (') character from a Python string](http://stackoverflow.com/questions/3151146/), [Remove specific characters from a string in python](http://stackoverflow.com/questions/3939361/) – outis Jan 19 '12 at 09:56

2 Answers2

40

Why a regex?

mystring = mystring.replace(",", "")

is enough.

Of course, if you insist:

mystring = re.sub(",", "", mystring)

but that's probably an order of magnitude slower.

Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522
  • I had the same issue with an exercise. The replace method is a nice toDo when the commas don't have spaces after. Otherwise, if it has a space after, it will create a double space. – Jcc.Sanabria Jan 14 '17 at 00:35
7

You don't need RE for that trivial operation. just use replace() on string:

a="123,asd,wer"
a.replace(",", "")
Michał Šrajer
  • 27,013
  • 6
  • 52
  • 75