Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Idiom to check if string is empty, print default

I'm just wondering, is there a Python idiom to check if a string is empty, and then print a default if it's is?

(The context is Django, for the __unicode__(self) function for UserProfile - basically, I want to print the first name and last name, if it exists, and then the username if they don't both exist).

Cheers, Victor

like image 760
victorhooi Avatar asked Dec 24 '09 01:12

victorhooi


People also ask

How do you check if a string is empty in Python?

Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string! Keep in mind that this only checks if a string is truly empty.

Is empty string true in Python?

Practical Data Science using PythonEmpty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.

What is displayed when we print an empty string in Python?

Output. 0. You can see that the length of the empty String in Python is 0. The 0 is also a boolean value. Python empty string is “falsy“, which means they are considered False in a Boolean context.


2 Answers

displayname = firstname+' '+lastname if firstname and lastname else username
like image 115
Federico A. Ramponi Avatar answered Oct 19 '22 23:10

Federico A. Ramponi


displayname = firstname + lastname or username

will work if firstname and last name has 0 length blank string

like image 4
YOU Avatar answered Oct 19 '22 22:10

YOU