Introduction to Python Resources

Begin your free Python journey now,
at your own pace

check

Syntax: Checking Strings

check

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:

  1. 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.
  2. If there is any misspelling or typo in your code, Python will interpret it as a different value.
  3. Strings are case-sensitive: if anything is capitalized differently it won't match.
  4. 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:

  1. Create a variable named phrase and assign it the string "This is a testing string".

  2. Create a variable named starts_with_bool and using the phrase variable and .startsWith() method, assign the starts_with_bool variable a True value.

  3. Print the value contained in the starts_with_bool variable.

  4. Create a variable named ends_with_bool and using the phrase variable and .endsWith() method, assign the ends_with_bool variable a True value.

  5. Print the value contained in the ends_with_bool variable.

  6. Create a variable named alpha_string and assign it the string "HeyThere".

  7. Create a variable named alpha_bool, and using the alpha_string variable and .isalpha() method, assign the alpha_bool variable a True value.

  8. Print the value contained in the alpha_bool variable.

  9. Create a variable named numeric_string and assign it the string "12345".

  10. Create a variable named numeric_bool, and using the numeric_string variable and .isnumeric() method, assign the numeric_bool variable a True value.

  11. Print the value contained in the numeric_bool variable.

  12. Create a variable named space_string and assign it a string with three spaces.

  13. Create a variable named space_bool, and using the space_string variable and .isspace() method, assign the space_bool variable a True value.

  14. Print the value contained in the space_bool variable.

  15. Create a variable named favorite_movie and assign it a string value that represents your favorite movie.

  16. Using the favorite_movie variable and the proper string method, print a boolean value which indicates if the title of your favorite movie is all uppercase.

  17. Using the favorite_movie variable and the proper string method, print a boolean value which indicates if the title of your favorite movie is all lowercase.

  18. Using the favorite_movie variable 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
    *Hints are best viewed after completing a task, or after spending some time and effort attempting it. In cases where a hint contains example output, it is important to understand why it is correct, as there may be many correct outputs.

    > True
    > True
    > True
    > True
    > True
    output varies for last three outputs
    > False
    > False
    > True

    SOLUTION*: Click here for an example solution
    *Example solutions are best viewed after completing a task and understanding the outcome. In most cases, there are multiple ways to complete a task, and the example solution is only one example.
    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!