Python check if string ends with a specific character

Document 对象参考手册Python3 Examples

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)

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。

Document 对象参考手册Python3 Examples

Other extensions