s = input("输入一个包含整数的字符串:")
ss = s.split(" ")
numbers = {}
tpl = ""
i = 0
for v in ss:
if v.isdigit():
numbers["number{}".format(i)] = int(v)
tpl+="{number"+str(i)+":010}"
i+=1
else:
tpl += " " + v + " "
print(tpl)
print(tpl.format_map(numbers))
print(numbers)
方法2
s = input("请输入一个包含整数的字符串:")
dict = {}
index = 0
ss = "" #用来存储模板字符串
number = "" #用来存储数字
for i in range(len(s)):
c = s[i]
if ord(c)in range(48,58): #判断是否为数字型字符,ord函数用来将字符转换为Ascii码
number += c
else:
if len(number) > 0:
ss += "{{number{}:010}}".format(index)
dict["number" + str(index)] = int(number) #为字典赋值
number = ""
index += 1
ss += c
#处理以数字结尾的情况,因为最后一次循环之后,并不会执行上述的else语句。
# 所以需要为其单独添加一个用来添加键值对的语句
if len(number) > 0:
ss += "{{number{}:010}}".format(index)
dict["number" + str(index)] = int(number)
print(ss)
print(ss.format_map(dict))