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)
有没有更好的方法呢?
谢谢
当您找到第一个非数字字符时,您可以突破循环
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)
您可以使用正则表达式将字符串分成组:
>>> 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)
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)
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)
| 归档时间: |
|
| 查看次数: |
6155 次 |
| 最近记录: |