[英]In Python, If I split a string up, how do i check if each part of it is an integer
例如,如果我的输入是“ 1 2 3”,如何检查每个部分是否为整数而不是其他任何内容,如果还有其他内容,则可以再次输入字符串,以使其正确无误,否则它将无法继续
>>> s = "1 2 3"
>>> all([i.isdigit() for i in s.split()])
True
>>> l = "1 b 2 5 c"
>>> all([i.isdigit() for i in l.split()])
False
The following reads from standard input and keeps reading until a string is received with space-separated integers. 以下内容从标准输入中读取并保持读取状态,直到接收到以空格分隔的整数作为字符串为止。 Finally it prints that it got all integers:
最后,它输出所有整数:
s = raw_input('Enter your input:')
while not all((p.isdigit() for p in s.split(" "))):
print("Not all integers")
s = raw_input('Enter your input:')
print("Got all integers!")
You can split you string to a list using list1=s.split() 您可以使用list1 = s.split()将字符串拆分为列表
And then check wether each of them is a integer or not. 然后检查它们是否为整数。
Ugly code, but it does what you want: 丑陋的代码,但是可以满足您的要求:
import re
integers = re.compile('[^\d\s]')
while True:
s = input("Enter integers: ")
if not integers.match(s):
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.