How to Check if String Ends with Specific Character in Python
In Python, you can check if a string ends with a specific character using the
endswith() method. For example, my_string.endswith('a') returns True if my_string ends with the character 'a', otherwise False.Syntax
The endswith() method checks if a string ends with the specified suffix (character or substring). It returns True if it does, otherwise False.
string.endswith(suffix): Checks ifstringends withsuffix.suffixcan be a single character or a substring.
python
string.endswith(suffix)
Example
This example shows how to check if a string ends with the character 'x' and prints the result.
python
my_string = "hellox" if my_string.endswith('x'): print("The string ends with 'x'.") else: print("The string does not end with 'x'.")
Output
The string ends with 'x'.
Common Pitfalls
One common mistake is to compare the last character manually without checking if the string is empty, which can cause errors. Another is to use == to compare the whole string instead of just the ending.
Also, endswith() is case-sensitive, so 'A' and 'a' are different.
python
my_string = "Hello" # Wrong: May cause error if string is empty # if my_string[-1] == 'o': # print("Ends with 'o'") # Right: Use endswith() safely if my_string.endswith('o'): print("Ends with 'o'") else: print("Does not end with 'o'")
Output
Ends with 'o'
Quick Reference
| Method | Description | Example | Returns |
|---|---|---|---|
| endswith(suffix) | Checks if string ends with suffix | my_string.endswith('a') | True or False |
| [-1] == char | Checks last character manually (risky if empty) | my_string[-1] == 'a' | True or False |
Key Takeaways
Use the endswith() method to check if a string ends with a specific character safely.
endswith() is case-sensitive; 'a' and 'A' are different characters.
Avoid accessing string[-1] without checking if the string is empty to prevent errors.
endswith() works with both single characters and longer substrings.
Use endswith() for clear, readable, and safe code.