在Python中用字符串中的单位分隔数字

dud*_*ein 6 python string units-of-measurement

我有包含数字及其单位的字符串,例如2GB,17ft等.我想将数字与单位分开并创建2个不同的字符串.有时,它们之间有一个空格(例如2 GB),并且使用split('')很容易做到.

当他们在一起时(例如2GB),我会测试每个角色,直到找到一个字母,而不是一个数字.

s='17GB'
number=''
unit=''
for c in s:
    if c.isdigit():
        number+=c
    else:
        unit+=c
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

谢谢

pwd*_*son 9

当您找到第一个非数字字符时,您可以突破循环

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

如果您有负数和小数:

numeric = '0123456789-.'
for i,c in enumerate(s):
    if c not in numeric:
        break
number = s[:i]
unit = s[i:].lstrip()
Run Code Online (Sandbox Code Playgroud)

  • 当单元丢失时,代码不会给出错误的结果。'10' -> number='1',unit='0'。为了解决这个问题,修改为`for i,c in enumerate(s+' '):` (2认同)

Jar*_*die 6

您可以使用正则表达式将字符串分成组:

>>> import re
>>> p = re.compile('(\d+)\s*(\w+)')
>>> p.match('2GB').groups()
('2', 'GB')
>>> p.match('17 ft').groups()
('17', 'ft')
Run Code Online (Sandbox Code Playgroud)

  • 要匹配更一般的数字集,包括"6.2"和"3.4e-27",需要更复杂的正则表达式.太糟糕的python没有内置的scanf模拟. (2认同)

Ign*_*ams 5

tokenize可以帮助:

>>> import StringIO
>>> s = StringIO.StringIO('27GB')
>>> for token in tokenize.generate_tokens(s.readline):
...   print token
... 
(2, '27', (1, 0), (1, 2), '27GB')
(1, 'GB', (1, 2), (1, 4), '27GB')
(0, '', (2, 0), (2, 0), '')
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 2

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