gpt4 book ai didi

python - 在python中的较大字符串中优雅地扩展某些子字符串

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:21 25 4
gpt4 key购买 nike

您好,我想在更大的字符串中优雅地将 4-6 类型的子字符串扩展为 4,5,6

s = "235:2,4,6-9,12,14-19;240:3,5-9,10;245:4,9,10-15,18"

print expand(s)
235:2,4,6,7,8,9,12,14,15,16,17,18,19;240:3,5,6,7,8,9,10;245:4,9,10,11,12,13,14,15,18

使用 Python。

是否有一些正则表达式巫术或类似的东西?非常感谢!

最佳答案

你可以这样做:

>>> import re
>>> def repl(match):
... start, end = match.groups()
... return ','.join(str(i) for i in range(int(start), int(end)+1))
...
>>> re.sub(r'(\d+)-(\d+)', repl, "235:2,4,6-9,12,14-19;240:3,5-9,10;245:4,9,10-15,18")
'235:2,4,6,7,8,9,12,14,15,16,17,18,19;240:3,5,6,7,8,9,10;245:4,9,10,11,12,13,14,15,18'

这使用了一个事实,即 re.subrepl 参数可以是将匹配作为参数并返回替换字符串的可调用对象。

expand(s) 函数将是:

import re

def repl(match):
start, end = match.groups()
return ','.join(str(i) for i in range(int(start), int(end)+1))

def expand(s):
return re.sub('(\d+)-(\d+)', repl, s)

关于python - 在python中的较大字符串中优雅地扩展某些子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15917814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com