对if语句中split()变量赋值的理解



到目前为止,只要我的第一个元素是单字母输入,我的代码就可以正常工作但是当我在第一个元素中输入多个字母时,不知怎么的,值没有分配给变量

我只是想理解为什么代码不赋值时,第一个元素是双或多个字母?

代码:

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

str.find()返回在字符串中找到子字符串的索引,否则返回-1。不返回TrueFalse

当第一个分隔符(-/)前有一个单位数时,str.find()返回1。在Python中,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('-')

find()不返回TrueFalse,它是一个偏移量:

返回子字符串sub在切片s[start:end]中找到的字符串中的最低索引。可选参数startend被解释为片表示法。如果未找到,返回-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)

最新更新