python中是否有一個模塊可以從給定范圍內的字串中獲取整數(有限制/限制)?
使代碼更干凈可能很有用。
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | bool: # (or False directly)
try:
number = int("".join(filter(str.isdigit, string)))
if low_boundary < number < high_boundary:
return number
else:
return False
except ValueError: # Empty message or out of limit
return False
用法:
...
if not amount := get_int_from_str(string=input(), low_boundary = 10, high_boundary = 20)
...
...
uj5u.com熱心網友回復:
不要與例外作斗爭。如果您無法將字串決議為整數,請ValueError引發。如果數字超出范圍,請提出不同的ValueError. 否則,回傳一個保證在請求范圍內的值。
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int:
x = int(str) # May raise
if x < low_boundary or x > high_boundary:
raise ValueError(f"Value '{x}' is out of range {low_boundary}-{high_boundary}")
return x
如果字串不能產生范圍內的整數,呼叫者比你的函式更清楚該怎么做,并且引發例外會迫使他們考慮最壞的情況,而不是讓他們假設函式作業并稍后遇到錯誤。
作為傳統的替代方法,您可以回傳None以指示缺少合適的int值。與False,不同,None不能與 混淆0,但仍然可以完全忽略它,以免以后出現問題。(并且None它本身并不會告訴您字串是否不可決議,或者決議的數字是否超出范圍。)
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
try:
x = int(str)
except ValueError:
return None
if x < low_boundary or x > high_boundary:
return None
return x
或者,為了避免重復return None宣告:
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
try:
x = int(str)
if x < low_boundary or x > high_boundary:
raise ValueError
except ValueError:
return None
return x
uj5u.com熱心網友回復:
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | False:
number = "".join(filter(str.isdigit, string))
if number:
number = int(number)
if low_boundary < number < high_boundary:
return number
return False
注意:對函式的輸出使用 not 運算子不會區分Falseand 0asnot False并且not 0將評估為True。在這里,您可以通過使用amount is not False條件檢查輸出來區分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404868.html
標籤:
上一篇:Discord.pyBot發送奇怪的嵌入文本而不是嵌入
下一篇:找不到模板檔案
