快速提问(使用Python 3.x) - 我正在编写一个Python程序,它接受多行输入,然后搜索该输入,查找所有整数,对它们求和,并输出结果。我有点难以找到最有效的搜索方式并找到多位整数 - 如果一行包含12,我想找到12而不是[1,2]。这是我的代码,未完成:
def tally():
#the first lines here are just to take multiple input
text = []
stripped_int = []
stopkey = "END"
while True:
nextline = input("Input line, END to quit>")
if nextline.strip() == stopkey:
break
text.append(nextline)
#now we get into the processing
#first, strip all non-digit characters
for i in text:
for x in i:
if x.lower() in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','!',',','?']:
pass
else:
stripped_int.append(x)
print(stripped_int)
tally()
这打印出一个包含所有整数的列表,但是我对如何将整数保持在一起感到困惑。有什么想法吗?
答案 0 :(得分:5)
使用正则表达式:
import re
def tally(string):
return map(int, re.findall(r'\b\d+\b', string))