DEV Community

Konstantinos Blatsoukas
Konstantinos Blatsoukas

Posted on

Python string methods examples

Here are some useful python string methods examples:

  • transform a sentece to title:
print("My python text".title())
# output
# My Python Text
Enter fullscreen mode Exit fullscreen mode
  • check the ending of a phrase, with endsWith():
# returns a boolean in case that the sentence ends with the
# provided parameter

print("My python text".endswith("."))
# False
print("My python text.".endswith("."))
# True
Enter fullscreen mode Exit fullscreen mode
  • remove any tabs, whitespaces from a given string (from the beginning and the end)
# returns a boolean in case that the sentence ends with the
# provided parameter

print("   My python text.   ".strip())
# My python text.
Enter fullscreen mode Exit fullscreen mode
  • find and replace words or string sequences:
print("I bake good cakes.".replace("good", "amazing"))
# I bake amazing cakes.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)