2

What is a neat way to remove different characters from a string? For example, I have the following strings that I need to convert to integers:

($12,990)
$21,434

I use the following code which works fine, but is there a less bulkier way to do the same?

string = string.replace(",", "")
string = string.replace("$", "")
string = string.replace("(", "-")
string = string.replace(")", "")
int(string)

Edit: I am using Python 2.7.

5
  • is string.replace("(", "-") a typo? That line doesn't remove a character... Commented Jul 12, 2017 at 22:35
  • 1
    @MSeifert It's Excel formatting for negative numbers to put parenthesis around them Commented Jul 12, 2017 at 22:37
  • This answer is most concise, but the whole thread is excellent, and shows that the problem is not entirely trivial. Commented Jul 12, 2017 at 22:44
  • 1
    @9000 only if - were both a value to be replaced and a value to replace. str.translate handles this nicely (and trivially). The question you marked as a duplicate does not seem to use str.translate at all. Commented Jul 12, 2017 at 22:45
  • 1
    @AdamSmith: Yes, for one-character case, str.translate is nice. This may suffice in this particular case. Commented Jul 12, 2017 at 22:47

3 Answers 3

7

You could use str.translate, e.g.

>>> "($12,990)".translate(str.maketrans({',': '', '$': '', '(': '-', ')': ''}))
'-12990'

As stated by @AdamSmith in the comments you could also utilize the (full) three-argument form of str.maketrans:

>>> translationtable = str.maketrans("(", "-", ",$)")
>>> "($12,990)".translate(translationtable)
'-12990'

In case you're using python-2.x the str.translate function and string.maketrans function can be used:

>>> import string
>>> translationtable = string.maketrans('(', '-')
>>> "($12,990)".translate(translationtable, ',$)')
'-12990'

or with unicodes on Python-2.x you need a unicode-ordinal to unicode-ordinal/string or None:

>>> unicode_translation_table = {ord(u','): None, ord(u'$'): None, ord(u'('): ord(u'-'), ord(u')'): None}
>>> u"($12,990)".translate(unicode_translation_table)
u'-12990'
Sign up to request clarification or add additional context in comments.

7 Comments

or str.maketrans("(", "-", ",$)") per the docs the three-argument version of maketrans pairs the first two arguments and maps the third to None (empty string)
I am getting an error AttributeError: type object 'str' has no attribute 'maketrans'. I guess that is because I am using Python 2.7. Is there a way to make it work in Python 2.7?
@sprogissd I included the python 2.7 way of solving it :)
I get this error translate() takes exactly one argument (2 given) when I use your solution in Python 2.7 and use a string variable instead of "($12,990)".
Seems like the error is caused by unicode. When I do string.encode('utf-8'), it works. Is there a way to do it using unicode?
|
0

Well, you can rely on a loop to make it less ugly:

FORBIDDEN_CHARS =  { # Model: { "Replacer" : "Replacees", ... }
 "" : ",$)", 
 "-" : "("
} 

for replacer in FORBIDDEN_CHARS:
 for replacee in FORBIDDEN_CHARS[replacer]:
  mystr = mystr.replace(replacee, replacer)

2 Comments

Yeah sorry for this, then you can rely on an associative dict, let me update
Updated :-) Sounds correct now
-1
''.join(string.strip('(').strip(')').strip('$').split(','))

or

''.join(filter(str.isdigit, string))

1 Comment

That does not handle parentheses correctly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.