我正在尝试编写一个程序,它会在输入的部分之前插入特定的数字,例如给定输入“171819-202122-232425”我希望它将数字拆分成碎片并使用短划线作为分隔符。我使用list(str(输入))拆分数字,但不知道如何插入适当的数字。它必须适用于任何数字感谢您的帮助。
输出=
(number)17
(number)18
(number)19
(number+1)20
(number+1)21
(number+1)22
(number+2)23
(number+2)24
(number+2)25
答案 0 :(得分:1)
您可以使用拆分和正则表达式来挖掘您的数字列表:
import re
mynum = "171819-202122-232425"
start_number = 5
groups = mynum.split('-') # list of numbers separated by "-"
number_of_groups = xrange(start_number , start_number + len(groups))
for (i, number_group) in zip(number_of_groups, groups):
numbers = re.findall("\d{2}", number_group) # return list of two-digit numbers
for x in numbers:
print "(%s)%s" % (i, x)
(5)17
(5)18
(5)19
(6)20
(6)21
(6)22
(7)23
(7)24
(7)25
答案 1 :(得分:0)
试试这个:
<强>代码:强>
mInput = "171819-202122-232425"
number = 9 # Just an example
result = ""
i = 0
for n in mInput:
if n == '-': # To handle dash case
number += 1
continue
i += 1
if i % 2 == 1: # Each two digits
result += "\n(" + str(number) + ")"
result += n # Add current digit
print result
<强>输出:强>
(9)17
(9)18
(9)19
(10)20
(10)21
(10)22
(11)23
(11)24
(11)25