What's the logical value of "string" in Python?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams
--
Chapters
00:00 What'S The Logical Value Of &Quot;String&Quot; In Python?
00:33 Answer 1 Score 2
00:45 Accepted Answer Score 13
01:21 Answer 3 Score 0
01:30 Answer 4 Score 2
01:43 Thank you
--
Full question
https://stackoverflow.com/questions/4531...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #casting #boolean
#avk47
ACCEPTED ANSWER
Score 13
Any non empty string in Python (and most other languages) is true as are all non-zero numbers and non-empty lists, dictionaries, sets and tuples.1
A nicer way to do what you want is:
name = input("what is your name?")
if name in ("Kamran", "Samaneh"):
print("That is a nice name")
else:
print("You have a boring name ;)")
This creates a tuple containing the names that you want and performs a membership test.
1 As delnan points out in the comments, this applies to all well written collections. That is, if you implement a custom collection class, make sure that it is false when it's empty.
ANSWER 2
Score 2
http://docs.python.org/library/stdtypes.html#truth-value-testing
"....All other values are considered true — so objects of many types are always true."
ANSWER 3
Score 2
In Python an empty string is considered False, True otherwise.
You could use the in operator:
if name in ("Kamran","Samaneh"):
print("That is a nice name")
else:
print("You have a boring name ;)")
ANSWER 4
Score 0
A non-empty string is True, yes. An empty one is False. This is super-handy.