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
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.
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.
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.
displayname = firstname+' '+lastname if firstname and lastname else username
displayname = firstname + lastname or username
will work if firstname and last name has 0 length blank string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With