Python check if string ends with a specific character
In Python, we can use the string'sendswith()method to check whether a string ends with a specific character or substring. This method returns a boolean value. If the string ends with the specified character or substring, it returnsTrue, otherwise it returnsFalse。
Example
# Define a string
text = "Hello, world!"
# Check whether the string ends with "world!"
result = text.endswith("world!")
# Output the result
print(result)
text = "Hello, world!"
# Check whether the string ends with "world!"
result = text.endswith("world!")
# Output the result
print(result)
Code explanation:
text = "Hello, world!": Define a string variabletext, whose value is"Hello, world!"。result = text.endswith("world!"): Useendswith()method to checktextwhether it ends with"world!", and store the result in the variableresult.print(result): Outputresultthe value of, i.e.,TrueorFalse。
Output result:
True
In this example, the string"Hello, world!"with"world!"ends with, thereforeendswith()method returnsTrue。
Python3 Examples