Python - Modify Strings
Strings in Python are immutable, meaning they can't be changed after they're created. But don’t worry — you can modify a string by creating a new string using Python’s built-in string methods.
This tutorial shows you how to modify strings using methods like upper()
, lower()
, replace()
, strip()
, and more.
Strings are Immutable in Python
You can’t change the characters in a string directly:
txt = "hello"
# txt[0] = "H" # ❌ This will raise an error
Instead, you create a new string using methods:
txt = "hello"
txt = txt.capitalize()
print(txt) # Output: Hello
Common String Modification Methods
1. upper()
– Convert to Uppercase
txt = "python"
print(txt.upper()) # Output: PYTHON
2. lower()
– Convert to Lowercase
txt = "PYTHON"
print(txt.lower()) # Output: python
3. strip()
– Remove Leading and Trailing Whitespace
txt = " Hello World "
print(txt.strip()) # Output: Hello World
4. replace()
– Replace Substrings
txt = "I like Java"
print(txt.replace("Java", "Python")) # Output: I like Python
5. split()
– Split String into a List
txt = "apple,banana,cherry"
fruits = txt.split(",")
print(fruits) # Output: ['apple', 'banana', 'cherry']
6. join()
– Join List into a String
words = ['Learn', 'Python']
result = " ".join(words)
print(result) # Output: Learn Python
7. capitalize()
– Capitalize First Letter
txt = "hello world"
print(txt.capitalize()) # Output: Hello world
8. title()
– Capitalize First Letter of Every Word
txt = "python string methods"
print(txt.title()) # Output: Python String Methods
9. find()
– Find Substring Index
txt = "Learn Python"
print(txt.find("Python")) # Output: 6
Real-World Example
Example: Clean up and format user input
user_input = " jOhN doE "
cleaned = user_input.strip().title()
print(cleaned) # Output: John Doe
Summary Table of Common Methods
Method | Description |
---|---|
upper() | Convert to uppercase |
lower() | Convert to lowercase |
strip() | Remove leading/trailing whitespace |
replace() | Replace part of string |
split() | Split string into list |
join() | Join list into string |
capitalize() | Capitalize first letter |
title() | Capitalize each word |
find() | Find position of substring |