Search code examples
pythonstringunits-of-measurement

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


Solution

  • s='17GB'
    for i,c in enumerate(s):
        if not c.isdigit():
            break
    number=int(s[:i])
    unit=s[i:]