Python Modify Strings
In Python, strings come with many built-in methods that allow you to modify, clean, and transform text easily.
Since strings are immutable, modification always returns a new string instead of changing the original one.
Upper Case (upper())
The
upper() method converts all characters in a string to uppercase.python
text = "python"
print(text.upper())
python
name = "Code Marathi"
print(name.upper())
python
print("hello world".upper())
Lower Case (lower())
The
lower() method converts all characters to lowercase.python
text = "PYTHON"
print(text.lower())
python
name = "AWS CLOUD"
print(name.lower())
python
print("Hello Python".lower())
Remove Whitespace (strip())
The
strip() method removes extra spaces from the beginning and end of a string.python
text = " Python "
print(text.strip())
python
name = " CodeMarathi"
print(name.strip())
python
print(" Hello World ".strip())
Replace String (replace())
The
replace() method replaces a part of the string with another string.python
text = "Hello World"
print(text.replace("World", "Python"))
python
language = "Java"
print(language.replace("Java", "Python"))
python
print("I like C".replace("C", "Python"))
Split String (split())
The
split() method breaks a string into a list based on a separator.python
text = "Python is easy"
print(text.split())
python
data = "apple,banana,orange"
print(data.split(","))
python
email = "user@gmail.com"
print(email.split("@"))
Capitalize First Letter (capitalize())
The
capitalize() method converts the first character to uppercase.python
text = "python"
print(text.capitalize())
python
name = "code marathi"
print(name.capitalize())
python
print("hello world".capitalize())
Title Case (title())
The
title() method converts the first letter of each word to uppercase.python
text = "python programming language"
print(text.title())
python
course = "aws cloud fundamentals"
print(course.title())
python
print("learn python easily".title())
Remove Specific Characters (lstrip() and rstrip())
lstrip()removes characters from the leftrstrip()removes characters from the right
python
text = "###Python"
print(text.lstrip("#"))
python
text = "Python###"
print(text.rstrip("#"))
python
text = "***Hello***"
print(text.strip("*"))
Check String Content (Useful Methods)
python
text = "Python123"
print(text.isalnum())
python
text = "Python"
print(text.isalpha())
python
text = "12345"
print(text.isdigit())
String Modification Does Not Change Original String
python
text = "python"
new_text = text.upper()
print(text)
print(new_text)
Summary
- Strings cannot be modified directly (immutable)
- Methods return a new modified string
- Common methods include
upper(),lower(),strip(),replace() - Splitting and formatting strings is easy in Python
- String methods help clean and format user input
Exercise
- Convert your name to uppercase
- Remove extra spaces from a string
- Replace a word in a sentence
- Split a sentence into words