0

Hello all,
I'll start by saying please bear with me, I am very new to python and I need some help takeing a string with mixed letters and numbers and converting it to a INT. For example

stringname = '105 mV'

I would like '105 'striped from the string. of course if you cast like:

intname = int(stringname)

you get an error (ValueError: invalid literal for int() with base 10: '105 mV')

So my question is, is there a method that will do this for me. Currently I do this:

intname = int(stringname.replace(' mV',''))

and is seems to work but somehow seems a little clumsy.

any suggestions???

Also if anyone knows of a good resource for sting methods I would very much appreciate you sharing with me.

Thanks
Chad

4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by crono5788
0

A general solution:

def str_to_int(s):
    return int(''.join([c for c in s if c in '1234567890']))

s = '105 mV'
print str_to_int(s)
0

Alternately if you knew there would always be a space after the number:

s = '105 mV'
number = s.split(' ')[0]
print number
0

thanks for you input, I will give these example a try.

Chad

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.