How to Check and Manipulate Strings in Python

Demonstrates core string inspection and transformation methods like case conversion, trimming, splitting, and membership checks on a sample string.

Easy Python 3.9+ Aug 9, 2026 Strings & text 16 views 0 copies

Python code

13 lines
Python 3.9+
text = "  Hello, Python Learners!  "

print(f"Original: '{text}'")
print(f"Lowercase: '{text.lower()}'")
print(f"Uppercase: '{text.upper()}'")
print(f"Title case: '{text.title()}'")
print(f"Stripped: '{text.strip()}'")
print(f"Length: {len(text)}")
print(f"Replace: '{text.replace('Python', 'Programming')}'")
print(f"Split: {text.split()}")
print(f"Contains 'Python': {'Python' in text}")
print(f"Starts with '  Hello': {text.startswith('  Hello')}")
print(f"Ends with '!': {text.endswith('!')}")

Output

stdout
Original: '  Hello, Python Learners!  '
Lowercase: '  hello, python learners!  '
Uppercase: '  HELLO, PYTHON LEARNERS!  '
Title case: '  Hello, Python Learners!  '
Stripped: 'Hello, Python Learners!'
Length: 29
Replace: '  Hello, Programming Learners!  '
Split: ['Hello,', 'Python', 'Learners!']
Contains 'Python': True
Starts with '  Hello': True
Ends with '!': True

How it works

Python strings are immutable objects, so each method like .lower() or .strip() returns a new string rather than modifying the original. The len() function counts every character including spaces, which is why the length returns 29. Methods such as .startswith() and .endswith() return boolean values, making them ideal for condition checks. The in operator performs a substring search and is the simplest way to test membership. The .split() method with no arguments splits on any whitespace, producing a list of words without extra spaces.

Common mistakes

  • Forgetting that strings are immutable and that methods return new strings
  • Confusing `.strip()` with `.replace()` when removing surrounding spaces
  • Counting spaces included in `len()` when expecting character count excluding whitespace

Variations

  1. Use `.lstrip()` and `.rstrip()` to remove spaces only from one side
  2. Use `text.split(',')` to split on a specific delimiter instead of whitespace

Real-world use cases

  • Validating and normalizing user input before storing in a database by stripping whitespace and case-insensitive checks.
  • Extracting search terms or tags from raw text by splitting and lowercasing for consistent query processing.
  • Formatting log messages or report titles with title case and checking prefixes in automation scripts.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.