我有一个这样的字符串
"44MB\n" (it can be anything ranging from 44mb, 44 MB, 44 kb, 44 B)
我想将 44
和 MB
从上面的字符串中分离出来。我写了这段代码来提取数字
import re
mystring = "44MB\n"
re.findall(r'\d+', mystring)
为了提取大小,我想避免使用 if 语句
,例如
if "kb" mystring.lower():
# Do stuffs
if .......
如何使用正则表达式提取尺寸信息
最佳答案
这个脚本:
import re
test_string = '44.5MB\n12b\n6.5GB\n12pb'
regex = re.compile(r'(\d+(?:\.\d+)?)\s*([kmgtp]?b)', re.IGNORECASE)
order = ['b', 'kb', 'mb', 'gb', 'tb', 'pb']
for value, unit in regex.findall(test_string):
print(int(float(value) * (1024**order.index(unit.lower()))))
将打印:
46661632
12
6979321856
13510798882111488
它以字节为单位找到的大小。
关于python - 从 Python 中的字符串中提取数字和大小信息(KB、MB 等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341000/