
Syntax: Checking Strings
Checking the contents of strings with Python operators and built-in string-checking functions.
Checking the Properties of a String
Sometimes it's useful to check an overall property of a string and get a "yes" or "no" answer. For that, there are some built-in Python ways to check properties that give back a boolean.
String Equality in Detail
One of the most useful things to check a string for is whether it is equal to a specific value. As introduced in the previous exercise, this can be done with the Python equality operator. This will evaluate to True if the characters of the string match and False if they don't.
signal_color = "Green"
print(signal_color == "Green")
> True
signal_color = "Red"
print(signal_color == "Green")
> False
However, for an equality comparison to return True, both strings must match exactly, character-for-character. If there is any difference at all, no matter how small, equality will evaluate to False.
print("Greenish" == "Green")
> False
print("Greeen" == "Green")
> False
print("green" == "Green")
> False
print(" Green " == "Green")
> False
Reviewing the examples above:
- Python does not understand languages: While different words, phrases, and sentences can have the same meaning for a human, Python has a much stricter definition of
equality. - If there is any misspelling or typo in your code, Python will interpret it as a different value.
- Strings are case-sensitive: if anything is capitalized differently it won't match.
- Whitespace matters: any extra/missing space will cause two strings to not match.
One of the most difficult things in dealing with strings is user input. It can be very difficult to compare user submitted values with expected values. However, certain functionality such as checking if two strings are equal after removing special casing and whitespace characters using the .lower() and .strip() methods is an example of the things you can do so standardize user input.
signal_color = " green "
safe_signal_color = "Green"
print(signal_color == safe_signal_color)
> False
cleaned_signal_color = signal_color.lower().strip()
cleaned_safe_signal_color = safe_signal_color.lower().strip()
print(cleaned_signal_color == cleaned_safe_signal_color)
> True
Checking String Characteristics with Built-In Methods
Sometimes, you don't need to know exactly what characters a string contains. Sometimes, you just want to know (for example) what characters it starts with, if it's capitalized, or if it only has numeric digits. There are various other built-in Python methods that can be used to quickly check some of these attributes.
The .startswith(...) and .endswith(...) methods can be used to verify whether a string starts or ends with a value:
thesis = "it was the best of times, it was the worst of times"
print(thesis.startswith("it was the best of times"))
> True
print(thesis.endswith("it was the worst of times"))
> True
The .isalpha() method can be used to verify whether a string only contains alphabetic characters:
print("Hello".isalpha())
> True
print("Hello there".isalpha())
> False
Likewise, the .isnumeric() method can be used to verify whether a string represents a written number:
print("3.14159265359".isnumeric())
> True
print("3 blind mice".isnumeric())
> False
The .isspace() method can be used to verify whether a string only contains whitespace:
print(" ".isspace())
> True
print(" . ".isspace())
> False
The .isupper(), .islower(), and .istitle() methods can be used to verify whether a string is all uppercase, all lowercase, or title case (respectively):
print("HELLO THERE".isupper())
print("hello there".isupper())
print("Hello There".isupper())
> True
> False
> False
print("HELLO THERE".islower())
print("hello there".islower())
print("Hello There".islower())
> False
> True
> False
print("HELLO THERE".istitle())
print("hello there".istitle())
print("Hello There".istitle())
> False
> False
> True
Practice: Checking Strings
Based on the information above. Complete the following steps:
-
Create a variable named
phraseand assign it the string "This is a testing string". -
Create a variable named
starts_with_booland using thephrasevariable and.startsWith()method, assign thestarts_with_boolvariable aTruevalue. -
Print the value contained in the
starts_with_boolvariable. -
Create a variable named
ends_with_booland using thephrasevariable and.endsWith()method, assign theends_with_boolvariable aTruevalue. -
Print the value contained in the
ends_with_boolvariable. -
Create a variable named
alpha_stringand assign it the string "HeyThere". -
Create a variable named
alpha_bool, and using thealpha_stringvariable and.isalpha()method, assign thealpha_boolvariable aTruevalue. -
Print the value contained in the
alpha_boolvariable. -
Create a variable named
numeric_stringand assign it the string "12345". -
Create a variable named
numeric_bool, and using thenumeric_stringvariable and.isnumeric()method, assign thenumeric_boolvariable aTruevalue. -
Print the value contained in the
numeric_boolvariable. -
Create a variable named
space_stringand assign it a string with three spaces. -
Create a variable named
space_bool, and using thespace_stringvariable and.isspace()method, assign thespace_boolvariable aTruevalue. -
Print the value contained in the
space_boolvariable. -
Create a variable named
favorite_movieand assign it a string value that represents your favorite movie. -
Using the
favorite_movievariable and the proper string method, print a boolean value which indicates if the title of your favorite movie is all uppercase. -
Using the
favorite_movievariable and the proper string method, print a boolean value which indicates if the title of your favorite movie is all lowercase. -
Using the
favorite_movievariable and the proper string method, print a boolean value which indicates if the title of your favorite movie is title cased.HINT*: Click here for a hint
> True
> True
> True
> True
> True
output varies for last three outputs> False
> False
> True
SOLUTION*: Click here for an example solution
phrase = "This is a testing string" starts_with_bool = phrase.startswith("This") print(starts_with_bool) ends_with_bool = phrase.endswith("ing") print(ends_with_bool) alpha_string = "Heythere" alpha_bool = alpha_string.isalpha() print(alpha_bool) numeric_string = "12345" numeric_bool = numeric_string.isnumeric() print(numeric_bool) space_string = " " space_bool = space_string.isspace() print(space_bool) favorite_movie = "The Shawshank Redemption" `answers vary` print(favorite_movie.isupper()) print(favorite_movie.islower()) print(favorite_movie.istitle())
When the above is completed and you are getting the proper output, you are ready to move onto the next exercise!