Case Conversion Methods in Python

Case Conversion Methods in Python (Syntax + Examples)

Python provides several built-in string methods to convert text between different cases (uppercase, lowercase, title case, etc.). Below are the key methods with syntax and examples:


1. upper() – Convert to Uppercase

Purpose: Converts all characters in a string to uppercase.
Syntax:

python

string.upper()

Examples:

python

text = "Hello, World!"
print(text.upper())  # Output: "HELLO, WORLD!"

filename = "data.txt"
print(filename.upper())  # Output: "DATA.TXT"

2. lower() – Convert to Lowercase

Purpose: Converts all characters in a string to lowercase.
Syntax:

python

string.lower()

Examples:

python

text = "PyThOn Is FuN"
print(text.lower())  # Output: "python is fun"

email = "USER@EXAMPLE.COM"
print(email.lower())  # Output: "user@example.com"

3. capitalize() – Capitalize First Letter

Purpose: Converts the first character to uppercase and the rest to lowercase.
Syntax:

python

string.capitalize()

Examples:

python

text = "hello world"
print(text.capitalize())  # Output: "Hello world"

name = "aLiCe"
print(name.capitalize())  # Output: "Alice"

4. title() – Convert to Title Case

Purpose: Capitalizes the first letter of each word (like a title).
Syntax:

python

string.title()

Examples:

python

text = "python programming is fun"
print(text.title())  # Output: "Python Programming Is Fun"

book = "the great gatsby"
print(book.title())  # Output: "The Great Gatsby"

5. swapcase() – Swap Cases

Purpose: Swaps uppercase letters to lowercase and vice versa.
Syntax:

python

string.swapcase()

Examples:

python

text = "Hello, WoRLD!"
print(text.swapcase())  # Output: "hELLO, WOrld!"

code = "PyThOn"
print(code.swapcase())  # Output: "pYtHoN"

6. casefold() – Aggressive Lowercase (Unicode Support)

Purpose: Similar to lower(), but more aggressive (handles special Unicode characters).
Syntax:

python

string.casefold()

Examples:

python

text = "Straße"  # German for "street"
print(text.casefold())  # Output: "strasse" (lowercase + special handling)

word = "İstanbul"
print(word.casefold())  # Output: "i̇stanbul" (better for case-insensitive comparisons)

Summary Table

MethodPurposeExample
upper()Convert to uppercase"hello".upper() → "HELLO"
lower()Convert to lowercase"WORLD".lower() → "world"
capitalize()Capitalize first letter"python".capitalize() → "Python"
title()Convert to title case"hello world".title() → "Hello World"
swapcase()Swap uppercase/lowercase"PyThOn".swapcase() → "pYtHoN"
casefold()Strong lowercase (Unicode)"Straße".casefold() → "strasse"

These methods are useful for text normalization, comparisons, and formatting. Let me know if you need more details! 🚀

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *