我想知道用戶是否在數(shù)字前輸入了空格。目前,如果您按下空格然后輸入數(shù)字,程序會忽略空格并在您剛剛輸入數(shù)字時看到它。我嘗試了在這個網(wǎng)站上找到的一些方法,但我一定遺漏了一些東西。import rewhile 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
1 回答

慕桂英4014372
TA貢獻1871條經(jīng)驗 獲得超13個贊
您的示例代碼中的問題是您enternum在檢查空格之前轉(zhuǎn)換為整數(shù)(從而刪除空格)。如果您只是在將其轉(zhuǎn)換為整數(shù)enternum[0].isspace() 之前進行檢查,它將檢測到空格。
不要忘記檢查用戶是否輸入了某些內(nèi)容,而不僅僅是按回車鍵,否則IndexError在嘗試訪問時會出現(xiàn)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)
...
您沒有具體說明為什么要禁止空格,因此您應(yīng)該考慮這是否是您真正想要做的。另一種選擇是使用enternum.isdecimal()(同樣,在轉(zhuǎn)換為 int 之前)檢查字符串是否僅包含十進制數(shù)字。
添加回答
舉報
0/150
提交
取消