DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python String Methods Explained Simply (Common Operations)

Strings have many built-in methods for common tasks. These methods return new strings and do not change the original.

Basic methods for changing case

text = "hello python"

print(text.upper())   # HELLO PYTHON
print(text.lower())   # hello python
print(text.title())   # Hello Python
print(text.capitalize())  # Hello python
Enter fullscreen mode Exit fullscreen mode

Removing whitespace

messy = "  hello  "

print(messy.strip())   # "hello"
print(messy.lstrip())  # "hello  "
print(messy.rstrip())  # "  hello"
Enter fullscreen mode Exit fullscreen mode

Finding and replacing

sentence = "I like cats and cats like me"

print(sentence.find("cats"))     # 7 (first position)
print(sentence.replace("cats", "dogs"))  # I like dogs and dogs like me
Enter fullscreen mode Exit fullscreen mode

Checking content

email = "user@example.com"

print(email.startswith("user"))  # True
print(email.endswith(".com"))    # True
print("123".isdigit())           # True
print("abc".isalpha())           # True
Enter fullscreen mode Exit fullscreen mode

Splitting and joining

words = "apple,banana,cherry"

word_list = words.split(",")
print(word_list)  # ['apple', 'banana', 'cherry']

new_string = "-".join(word_list)
print(new_string)  # apple-banana-cherry
Enter fullscreen mode Exit fullscreen mode

Simple examples

Clean user input:

name = "  Alice  "
clean_name = name.strip().title()
print(clean_name)  # Alice
Enter fullscreen mode Exit fullscreen mode

Count occurrences (use count method):

text = "hello hello world"
print(text.count("hello"))  # 2
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Methods like .upper(), .lower(), .strip() for formatting.
  • .find(), .replace() for searching and changing.
  • .startswith(), .endswith(), .isdigit() for checks.
  • .split() and .join() for lists and strings.

Practice common string methods on text. They are essential for cleaning and processing strings in Python programs.

Top comments (0)