“Trouble converting string to int in Django/Python”

Posted on Updated on

A little while ago I was browsing on Stackoverflow (great website!) for Django & Python stuff. This was maybe last year or so? What I was trying to do was cast a string to an int but I had all sorts of conversion errors. But then I found this thread ( http://stackoverflow.com/questions/7448531/trouble-converting-string-to-int-in-django-python ) and learned a really great yet stupid trick which is this:

a = int('0' + someString)

Adding a zero in front of a string guaranties me to have at least “0” in the string. Now, to be sure, you may extract all the digits from the “‘0’+someString” with a regular expression.

Brilliant this is useful! blogging so my future self will see.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s