Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate number from unit in a string in Python

I have strings containing numbers with their units, e.g. 2GB, 17ft, etc. I would like to separate the number from the unit and create 2 different strings. Sometimes, there is a whitespace between them (e.g. 2 GB) and it's easy to do it using split(' ').

When they are together (e.g. 2GB), I would test every character until I find a letter, instead of a number.

s='17GB'
number=''
unit=''
for c in s:
    if c.isdigit():
        number+=c
    else:
        unit+=c

Is there a better way to do it?

Thanks

like image 616
duduklein Avatar asked Feb 10 '10 20:02

duduklein


Video Answer


2 Answers

You can break out of the loop when you find the first non-digit character

for i,c in enumerate(s):
    if not c.isdigit():
        break
number = s[:i]
unit = s[i:].lstrip()

If you have negative and decimals:

numeric = '0123456789-.'
for i,c in enumerate(s):
    if c not in numeric:
        break
number = s[:i]
unit = s[i:].lstrip()
like image 125
pwdyson Avatar answered Sep 23 '22 19:09

pwdyson


You could use a regular expression to divide the string into groups:

>>> import re
>>> p = re.compile('(\d+)\s*(\w+)')
>>> p.match('2GB').groups()
('2', 'GB')
>>> p.match('17 ft').groups()
('17', 'ft')
like image 37
Jarret Hardie Avatar answered Sep 24 '22 19:09

Jarret Hardie