userin=input("enter a question")
示例问题/用户
我有10台pc,我把3台pc给了我的朋友,我还剩多少台?
我想做的事情=从用户给定的字符串中查找整数并减去整数
结果 10-3 = 7
我需要答案,以最简单的方式,可能的.Its高中(12年级)项目。我试过这个
import re
ab=input("enter ")
# \d is equivalent to [0-9].
p = re.compile('\d')
pr=p.findall(ab)
for i in pr:
print(i, end="")
建议我其他最好的代码来完成同样的任务。我也想把它减去
发布于 2021-03-08 16:42:08
首先,您不需要单独的数字,但是可以组合或多个的数字,所以regex应该是'\\d+'
(不要忘记字符串会吃反斜杠) r'\d+'
。
ab=input("enter ")
# \d is equivalent to [0-9].
p = re.compile(r'\d+')
pr = p.findall(ab)
if len(pr) == 2:
print(int(pr[0]) - int(pr[1]))
发布于 2021-03-08 16:43:13
你也可以不用正则表达式来解决这个问题。字符串有内置的isdigit()
方法,它将在这里帮助您:
userin=input("enter a question")
digits = [int(each) for each in userin.split() if each.isdigit()]
# -> [10, 3]
result = digits[0] - digits[1]
# -> 7
https://stackoverflow.com/questions/66533613
复制相似问题