Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to remove '$'?

Tags:

python

All I want to do is remove the dollar sign '$'. This seems simple, but I really don't know why my code isn't working.

import re
input = '$5'
if '$' in input:
    input = re.sub(re.compile('$'), '', input)
    print input

Input still is '$5' instead of just '5'! Can anyone help?

like image 658
user1899415 Avatar asked Jul 24 '26 01:07

user1899415


2 Answers

Try using replace instead:

input = input.replace('$', '')

As Madbreaks has stated, $ means match the end of the line in a regular expression.

Here is a handy link to regular expressions: http://docs.python.org/2/library/re.html

like image 67
squiguy Avatar answered Jul 25 '26 15:07

squiguy


In this case, I'd use str.translate

>>> '$$foo$$'.translate(None,'$')
'foo' 

And for benchmarking purposes:

>>> def repl(s):
...     return s.replace('$','')
... 
>>> def trans(s):
...     return s.translate(None,'$')
... 
>>> import timeit
>>> s = '$$foo bar baz $ qux'
>>> print timeit.timeit('repl(s)','from __main__ import repl,s')
0.969965934753
>>> print timeit.timeit('trans(s)','from __main__ import trans,s')
0.796354055405

There are a number of differences between str.replace and str.translate. The most notable is that str.translate is useful for switching 1 character with another whereas str.replace replaces 1 substring with another. So, for problems like, I want to delete all characters a,b,c, or I want to change a to d, I suggest str.translate. Conversely, problems like "I want to replace the substring abc with def" are well suited for str.replace.

Note that your example doesn't work because $ has special meaning in regex (it matches at the end of a string). To get it to work with regex you need to escape the $:

>>> re.sub('\$','',s)
'foo bar baz  qux'

works OK.

like image 32
mgilson Avatar answered Jul 25 '26 15:07

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!