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.
Python code
13 linestext = " 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
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
- Use `.lstrip()` and `.rstrip()` to remove spaces only from one side
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.