[英]How do I differentiate between a string and a negative integer in python
我正在嘗試在我的函數中使用 while 循環,但在輸入數據輸入字符串時遇到問題。 下面是我的代碼。
search = input('Enter a string to continue or a negative number to exit:')
while True:
if int(search) < 0:
print('its a -ve number')
break
elif type(search) == str:
print('Its a string OK lets run the code and search')
else:
print('Please enter a valid input')
輸入字符串時出現 ValueError;
ValueError:以 10 為底的 int() 的無效文字:字符串值
要將字符串轉換為 integer,常用方法是將邏輯包裝在將處理值錯誤的 try except 塊中。 為了提高可讀性,我建議創建一種方法來處理值錯誤,如果發生則返回None
。
def parse_int(value):
try:
return int(value)
except ValueError:
return None
現在你的循環看起來像這樣:
while True:
int_search = parse_int(search)
if int_search is not None and int(search) < 0:
print('its a -ve number')
break
elif type(search) == str:
print('Its a string OK lets run the code and search')
else:
print('Please enter a valid input')
另請注意, input
function 始終返回一個字符串。 因此檢查type(search) == str
將始終返回 true。 也許您的意思是排除正數?
您還在循環之外構建input
,這意味着錯誤的選項將永遠循環,告訴您輸入了錯誤的數據。 將該輸入請求放在循環內。
while True:
search = input('Enter a string to continue or a negative number to exit:')
int_search = parse_int(search)
if int_search is not None and int(search) < 0:
print('its a -ve number')
break
elif int_search is not None:
print('Please enter a valid input')
else:
print('Its a string OK lets run the code and search')
如果收到值錯誤,另一種選擇可能是修改parse_int
方法以返回原始字符串值。 在這種情況下,類型將是search: Union[str, int]
。 邏輯可能如下所示(添加類型注釋以顯示它們如何有用):
from typing import Union
# Type annotations help document code and can be
# used by static analysis tools like mypy to catch bugs!
def parse_int(value: str) -> Union[str, int]:
try:
return int(value)
except ValueError:
return value
prompt = 'Enter a string to continue or a negative number to exit:'
while True:
search = parse_int(input(prompt))
# isinstance is the preferred way to check types.
if isinstance(search, int) and search < 0:
print('its a -ve number')
break
elif isinstance(search, str):
print('Its a string OK lets run the code and search')
else:
print('Please enter a valid input')
# Will bring us back to the start of the loop
# Causing us to get a fresh input value
continue
while 循環的第一個 if 條件將輸入轉換為int
。 這意味着如果輸入不是 integer,它將返回錯誤,因為無法將字符串轉換為 int。 所以試試這個:
search = input('Enter a string to continue or a negative number to exit:')
while True:
if search[0] == "-":
if search[1].isdigit():
print('its a -ve number')
break
elif type(search) == str:
print('Its a string OK lets run the code and search')
break
else:
print('Please enter a valid input')
break
有很多解決方案,如果您不想使用try/except
塊,可以使用regex
。 我們可以使用正則表達式匹配一個負數re.match('^-\d+$', search)
。 isnumeric()
如果在search
中找到字符串字符,將返回False
。 請記住,while 循環是連續運行的。
import re
search = input('Enter a string to continue or a negative number to exit: ')
while True:
if re.match('^-\d+$', search):
print('its a -ve number')
break
elif search.isnumeric() is False:
print('Its a string OK lets run the code and search')
else:
print('Please enter a valid input')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.