【发布时间】:2019-11-06 18:06:37
【问题描述】:
我正在使用 Python 2.7.13 来清理一些数据。
我有一个数字列表,如果字符串以数字开头。如果起始数字小于100,我需要用'100 BLOCK'替换它。如果数字更大,我需要用'00 BLOCK' 替换最后两位数。
保证文本列表以 0 或更大的数字开头。
例子
'1234 foo foo' --> '1200 BLOCK FOO FOO'
'19 bar bar' --> '100 BLOCK bar bar'
'0 baz baz' --> '100 BLOCK baz baz'
目前,我在 for 循环中运行两个不同的正则表达式:
for row in listOfNumbers:
/* Replace last two digits with '00 BLOCK' */
firstRegex = re.sub(r'^(\d*)\d{2}\b', r'\g<1>00 BLOCK', row)
/* Replace digits under 100 with '100 BLOCK'. This includes 0 */
secondRegex = re.sub(r'^(\d{1,2})\b', '100 BLOCK', firstRegex)
/* Do other stuff with results
是否有可能在一个正则表达式中以某种方式做到这一点?
【问题讨论】:
标签: regex python-2.7 list