I have a collection of strings like:
"0"
"90/100"
None
"1-5%/34B-1"
"-13/7"
I would like to convert these into integers (or None
) so that I start picking numbers from the beginning and stop at the first non-number character. The above data would thus become:
0
90
None
1
None
I tried doing something like the code below, but ran into multiple problems, like causing ValueError
with that int(new_n)
line when new_n
was just empty string. And even without that, the code just looks horrible:
def pick_right_numbers(old_n):
new_n = ''
numbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
if old_n is None:
return None
else:
for n in old_n:
if n in numbers:
new_n += n
else:
return int(new_n)
if new_n:
return int(new_n)
else:
return None
Could someone nudge me to the right direction with this?