检测前导空格-Python
我想知道用户是否在数字前输入了空格。当前,如果您按空格键,然后输入一个数字,程序将忽略该空格,并将其视为您刚刚输入的数字 我尝试了一些在这个网站上找到的方法,但我肯定错过了什么检测前导空格-Python,python,Python,我想知道用户是否在数字前输入了空格。当前,如果您按空格键,然后输入一个数字,程序将忽略该空格,并将其视为您刚刚输入的数字 我尝试了一些在这个网站上找到的方法,但我肯定错过了什么 import re while True: enternum=input('Enter numbers only') try: enternum=int(enternum) except ValueError: print
import re
while True:
enternum=input('Enter numbers only')
try:
enternum=int(enternum)
except ValueError:
print ('Try again')
continue
conv = str(enternum) # converted it so I can use some of the methods below
if conv[0].isspace(): # I tried this it does not work
print("leading space not allowed")
for ind, val in enumerate(conv):
if (val.isspace()) == True: # I tried this it does not work
print('leading space not allowed')
if re.match(r"\s", conv): # I tried this it does not work (notice you must import re to try this)
print('leading space not allowed')
print('Total items entered', len(conv)) # this does not even recognize the leading space
print ('valid entry')
continue
示例代码中的问题是在检查空格之前将
enternum
转换为整数(从而删除空格)。如果在将其转换为整数之前只选中enternum[0].isspace()
,它将检测空间
不要忘记检查用户是否输入了内容,而不是仅仅按enter键,否则在尝试访问enternum[0]
时,您将得到一个索引器
while True:
enternum = input('Enter numbers only')
if not enternum:
print('Must enter number')
continue
if enternum[0].isspace():
print('leading space not allowed')
continue
enternum = int(enternum)
...
<>你没有指定为什么你要特别禁止空间,所以你应该考虑这是否是你真正想要做的。另一个选项是使用enternum.isdecimal()
(同样,在转换为int之前)检查字符串是否只包含十进制数字。执行int(enternum)
时,删除了前导空格。没有什么可探测的了。