Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active July 21, 2019 05:51
Show Gist options
  • Save estysdesu/a2602a7afd916699eafec213ceba4a12 to your computer and use it in GitHub Desktop.
Save estysdesu/a2602a7afd916699eafec213ceba4a12 to your computer and use it in GitHub Desktop.
[Python: falsey strings and string comparison] #strings #falsey #python
#!/usr/bin/env python3
# https://github.com/keystroke3/redpaper/issues/1#event-2480042391
def empty_string_checker(s):
if not s: # this is equivalent to saying `if s == "":`
print("String is empty!")
if s: # this is equivalent to saying `if s != "":`
print("String is not empty -- it contains '{}'".format(s))
g = ""
empty_string_checker(g) # --> String is empty!
f = "hiya there"
empty_string_checker(f) # --> String is not empty -- it contains 'hiya there'
def string_compare(s):
if s != "hi" or s != "Hi" or s != "HI" or s != "hI": # this is equivalent to saying `if not s.lower():`
print("String does not equal 'hi' in any upper or lower case combination")
if s.lower() == "hi": # instead of checking all the possible case combinations of "hi" we can just check if the lowercase instance (or uppercase) of the variable is equal to the lowercase string we want
print("String does equal 'hi' and we only had to do one check! -- string: '{}'".format(s))
p = "hello"
string_compare(p) # --> String does not equal 'hi' in any upper or lower case
j = "hI"
string_compare(j) # --> String does equal 'hi' and we only had to do one check! -- string: 'hI'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment