Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

python - Understandings of split() variable assignation in if statement

so far my code working perfectly as long as my first element is single-letter input but somehow value is not assigning to a variable when I input multiple letters to the first element

I just want to understand why the code is not assigning value when the first element is double or multiple letters?

Code:

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)

Output Case 1:

Enter the date: 0-0-0
0 0 0

Output Case 2:

Enter the date: s/ss/ssss
s ss ssss

Output Case 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

Output Case 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
question from:https://stackoverflow.com/questions/65896303/understandings-of-split-variable-assignation-in-if-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

str.find() returns the index where the substring is found in the string, or -1 if not. It does not return True or False.

When you have a single digit before the first delimiter (- or /) str.find() returns 1. In Python, 1 also happens to be equal to True.

>>> True
True
>>> int(True)
1
>>> True == 1
True

That's why it works if there is a single character before the - or /.

In any other case find() returns -1 if the substring is not found. or a larger number, e.g. 2 neither of which is equal to True.

>>> 2 == True
False
>>> -1 == True
False

Fix your code by testing whether find() returns -1:

if date.find('-') == -1:
    dd, mm, yy = date.split('-')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...