使用xrange的Python字符串操作

时间:2011-03-24 14:17:06

标签: python string

操作myInput字符串以获得myOutput字符串的更快方法是什么?

myInput  = "1,3-5,7"

myOutput = "1,3,4,5,7"

3 个答案:

答案 0 :(得分:1)

我记得有关SO的问题将[1,3,4,5,7]变成了“1,3-5,7”,但我不记得是哪个

这是相反的问题:

def expand(s): 
    return ','.join(sum([v if len(v)==1 else map(str, apply(lambda a,b: range(a,b+1), map(int, v))) for v in [p.split('-') for p in s.split(',')]],[]))

print expand("1,3-5,7")

打印:

1,3,4,5,7

答案 1 :(得分:1)

re.sub( 
      "(\d+)-(\d+)" ,        
      lambda x : ",".join( map( str , range( int(x.group(1)) , int( x.group(2) ) +1 ) )) , 
      "1,3-5,7" )

你可以得到“1,3,4,5,7”

答案 2 :(得分:1)

>>> def expand(s):
...   for p in s.split(","):
...     r = p.split("-")
...     if len(r) == 1:
...       yield str(r[0])
...     else:
...       for i in range(int(r[0]), int(r[1]) + 1):
...         yield str(i)
... 
>>> ",".join(expand("1,3-5,7"))
'1,3,4,5,7'
>>> ",".join(expand("1-5,8,10,13-19"))
'1,2,3,4,5,8,10,13,14,15,16,17,18,19'

显然,如果输入不符合假设(字母,反向序列等),这将以各种有趣的方式失败,并且它不适用于负数。