Python String Methods: A Comprehensive Guide

This document provides a comprehensive overview of Python’s built-in string methods, organized by category. Each method includes a brief description, a Python code example, and the corresponding output. Strings in Python are immutable, so these methods return new strings without modifying the original.

1. Case Conversion Methods

These methods modify the case of characters in a string.

capitalize()

Capitalizes the first character and converts the rest to lowercase.

text = "hello WORLD"
result = text.capitalize()
print(result)

Output: Hello world

casefold()

Converts the string to lowercase, suitable for case-insensitive comparisons (more aggressive than lower()).

text = "ßtrAßE"
result = text.casefold()
print(result)

Output: strasse

lower()

Converts all characters to lowercase.

text = "Hello WORLD"
result = text.lower()
print(result)

Output: hello world

upper()

Converts all characters to uppercase.

text = "Hello World"
result = text.upper()
print(result)

Output: HELLO WORLD