到目前为止,只要我的第一个元素是单字母输入,但是当我向第一个元素输入多个字母时,值就不会分配给一个变量,我的代码就能很好地工作。
我只是想了解为什么当第一个元素是双字母或多个字母时,代码没有赋值?
代码:
date=input("Enter the date: ")
if date.find('-')==True:
dd,mm,yy=date.split('-')
elif date.find('/')==True:
dd,mm,yy=date.split('/')
else:
print('Incorrect Input',date)
print(dd,mm,yy)产出案例1:
Enter the date: 0-0-0
0 0 0产出案例2:
Enter the date: s/ss/ssss
s ss ssss产出案例3:
Enter the date: 10-10-10
Incorrect Input 10-10-10
Traceback (most recent call last):
File "C:\**\**\**\**\**", line 8, in <module>
print(dd,mm,yy)
NameError: name 'dd' is not defined产出案例4:
Enter the date: ss/sss/ss
Incorrect Input ss/sss/ss
Traceback (most recent call last):
File "C:\**\**\**\**\**", line 8, in <module>
print(dd,mm,yy)
NameError: name 'dd' is not defined发布于 2021-01-26 05:39:33
str.find()返回在字符串中找到子字符串的索引,如果没有,则返回-1。它不返回True或False。
当在第一个分隔符(-或/)之前有一个数字时,str.find()返回1。在str.find()中,1也恰好等于True。
>>> True
True
>>> int(True)
1
>>> True == 1
True这就是为什么在-或/之前只有一个字符才能工作的原因。
在任何其他情况下,如果找不到子字符串,find()将返回-1。或者更大的数字,例如2,两者都不等于True。
>>> 2 == True
False
>>> -1 == True
False通过测试find()是否返回-1来修复代码:
if date.find('-') == -1:
dd, mm, yy = date.split('-')发布于 2021-01-26 05:34:01
find()不返回True或False,这是一种抵消
返回字符串中的最低索引,其中在片
s[start:end]中找到子字符串子。可选参数开始和结束被解释为片表示法。如果找不到sub,则返回-1。
因此,您的代码变成:
date=input("Enter the date: ")
if date.find('-') != -1:
dd,mm,yy=date.split('-')
elif date.find('/') != -1:
dd,mm,yy=date.split('/')
else:
print('Incorrect Input',date)
print(dd,mm,yy)https://stackoverflow.com/questions/65896303
复制相似问题