-2

I have a dictionary "item":

>>> item["value"]
Out[2]: u'$26,420'

I want to convert this to the integer

26420

to load into a db. So far I've tried:

Out[2]: u'$26,420'
>>> item["value"][1:]
Out[3]: u'26,420'
>>> int(item["value"][1:])
Traceback (most recent call last):
  File "F:\envs\virtalenvs\teat\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-cd6c9e68ae50>", line 1, in <module>
    int(item["value"][1:])
ValueError: invalid literal for int() with base 10: '26,420'

Whats the best pythonic way to do this?

user1592380
  • 34,265
  • 92
  • 284
  • 515

3 Answers3

5

Strip away all non-numeric characters:

>>> s = '$26,420'
>>> s = ''.join(c for c in s if c.isnumeric())
>>> int(s)
26420
John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • Thanks John is "c for c in s if c.isnumeric()" a comprehension? I want to read up more on this. – user1592380 Jun 06 '16 at 17:41
  • 1
    Yes -- it is a comprehension (in the form of a generator-expression rather than a list-comprehension -- note the absence of square brackets). In my opinion such things are what makes Python really shine. A good way to learn them is to read the Python questions on Stack Overflow. Every single day you'll see at least a dozen examples in the answers. – John Coleman Jun 06 '16 at 18:10
2
some_amount = "$12,345"
some_amount = int(some_amount.split("$")[1].replace(",", ""))
print some_amount #Will return 12345 as an int
Bubble Hacker
  • 6,425
  • 1
  • 17
  • 24
2

You could chain two simple replaces together:

cur = int(cur.replace("$", "").replace(",", ""))
heinst
  • 8,520
  • 7
  • 41
  • 77