🔤

How to Use String Methods in Python

PythonBeginner

Master common string manipulation methods.

Code Example

Python
# String Methods in Python
text = "  Hello, World!  "

# Basic methods
print(text.strip())        # Remove whitespace
print(text.upper())        # Uppercase
print(text.lower())        # Lowercase
print(text.replace("World", "Python"))

# Splitting and joining
words = "apple,banana,cherry"
fruits = words.split(",")
print(f"\nSplit: {fruits}")
print(f"Join: {' | '.join(fruits)}")

# Checking methods
email = "user@example.com"
print(f"\nEnds with .com: {email.endswith('.com')}")
print(f"Contains @: {'@' in email}")
print(f"Is digit: {'123'.isdigit()}")

# Formatting
name = "Alice"
age = 30
print(f"\n{name} is {age} years old")
print("Pi is {:.2f}".format(3.14159))

Explanation

Python strings have many built-in methods for manipulation. strip() removes whitespace, split() breaks into lists, join() combines lists into strings.

Related Tutorials