python - 如何在带有 if 的辅助函数中使用 isdigit() 方法
问题描述
cani 如何使用 isdigit 方法 像那样if self.month.isdigit():
需要知道我的输入是否是数字
class myclass():
def __init__(self,year,month,day):
self.mah = ['none','farvardin','ordibehesht','khordad','tir','mordad','shahrivar','mehr','aban','azar','dey','bahman','esfand']
self.daylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
self.year = year
self.month = month
self.day = day
def myfunc(self):
if self.month.isdigit(): # problem is (isdigit) not working
p1= input("Please enter date:")
year,month,day = p1.split('-')
p2 = myclass(year,month,day)
p2.myfunc()
解决方案
@Tiago 据我了解,我已经更新了您的代码。当您从标准输入中获取输入时,p1 将只是一个字符串对象,但如果 p1 中没有任何“-”,那么代码将生成解包错误。例如,如果您通过20211114。
Please enter date:
Traceback (most recent call last):
File "jdoodle.py", line 19, in <module>
year,month,day = p1.split('-')
ValueError: not enough values to unpack (expected 3, got 1)
我已将您的班级名称从range更改为 CustomRange
加上我使用列表理解的日程表变量。
class CustomRange(): def __init__(self,year,month,day): self.daylist = [i for i in range(1,32)] self.year = year self.month = month self.day = day self.mah = ['none','farvardin','ordibehesht','khordad','tir','mordad','shahrivar','mehr','aban','azar','dey','bahman','esfand'] def myfunc(self): if self.month.isdigit(): # problem is (isdigit) not working print(self.month, "is number") return True else: print(self.month, "is not number") return False p1= input("Please enter date: ") year,month,day = p1.split('-') p2 = CustomRange(year,month,day) p2.myfunc()
推荐阅读
- python - Django不断返回分配错误之前引用的局部变量“产品”
- php - 如何使用 preg_replace_callback 而不是 preg_replace 用链接 html 替换单词?
- python - “找不到任何有价值的窗口提供程序”错误
- python - 如何进一步优化这段代码?
- lstm - 如何使用二进制标签计算 LSTM 的累积分数?
- wso2dss - WSO2EI DSS 中未发现 ERP 操作错误
- swift - GKState:为什么 StateMachine == nil 代表调用?
- php - 我想通过比较两个索引从嵌套关联数组中删除
- c# - 在 ListBoxItem DataTemplate 内的嵌套控件中处理相同的单击事件 - WPF
- c# - Listview 行工具提示显示持续时间