Reputation: 3135
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?
Upvotes: 2
Views: 1378
Reputation: 12218
You need to escape the dollar sign - otherwise python thinks it is an anchor http://docs.python.org/2/library/re.html
import re
fred = "$hdkhsd%$"
print re.sub ("\$","!", fred)
>> !hdkhsd%!
Upvotes: 1
Reputation: 310167
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.
Upvotes: 4
Reputation: 30483
Aside from the other answers, you can also use strip()
:
input = input.strip('$')
Upvotes: -1
Reputation: 33380
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
Upvotes: 7
Reputation: 883
$ is a special character in regular expressions that translates to 'end of the string'
you need to escape it if you want to use it literally
try this:
import re
input = "$5"
if "$" in input:
input = re.sub(re.compile('\$'), '', input)
print input
Upvotes: 2