-2

I want to turn a string like "$1,234.56" into 1234.56 so I can add it to a database, my current solution is using re.sub("[^0-9]", "", str1 this however strips the punctuation too, is there a way to keep it?

I'm using python 3.6.5

4
  • I'm sure this is a duplicate of a regex question, but going to answer it anyway. Commented Apr 22, 2018 at 2:01
  • if you know it will always be '$' and ',' that you will strip off, I think you can use re.sub("[$,]",'' str1) Commented Apr 22, 2018 at 2:03
  • stackoverflow.com/questions/37580151/… Commented Apr 22, 2018 at 2:17
  • I tried the "re.sub("[$,]",'' str1)" method, it gave me a Syntax Error Commented Apr 22, 2018 at 2:17

1 Answer 1

2

re.sub("[^0-9.]", "", str1)

will keep the decimal dot too. Is there any other punctuation you want to keep?

Note that this will still fail to produce a valid integer on inputs with more than one decimal dot, such as 123..45 or 1.2.3 or . or 1. or anything that looks weird.

The code discards everything but numbers and points, with no regard as to how many points or numbers are there. An infeasible number such that 223523523948231472389523 will still be kept, and depending on the way your database works (whether or not it can store numbers above 64 bits), the resulting number stored in the database may be negative or truncated!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.