[英]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.