The Python Oracle

What's the logical value of "string" in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC C Schuberts Piano Sonata No 13 D

--

Chapters
00:00 Question
00:41 Accepted answer (Score 13)
01:29 Answer 2 (Score 7)
02:19 Answer 3 (Score 2)
02:38 Answer 4 (Score 2)
02:55 Thank you

--

Full question
https://stackoverflow.com/questions/4531...

Answer 1 links:
[this page for a full list of values of all types that evaluate to ]: http://docs.python.org/library/stdtypes....

Answer 3 links:
http://docs.python.org/library/stdtypes....

--

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.