How to Manipulate Strings in Python | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
Python

How to Manipulate Strings in Python

Learn essential string operations in Python including slicing, formatting, and common methods.

PythonStringsText ProcessingData Types

Strings are one of the most commonly used data types in Python. Here’s how to work with them effectively.

Creating Strings

# Single or double quotes
single = 'Hello'
double = "World"

# Multi-line strings
multi = """This is a
multi-line string"""

# Raw strings (ignore escape characters)
raw = r"C:\Users\name\Documents"
print(raw)  # C:\Users\name\Documents

String Indexing and Slicing

text = "Hello, World!"

# Indexing (0-based)
print(text[0])   # H
print(text[-1])  # !

# Slicing [start:end:step]
print(text[0:5])   # Hello
print(text[7:])    # World!
print(text[:5])    # Hello
print(text[::2])   # Hlo ol!
print(text[::-1])  # !dlroW ,olleH (reversed)

Common String Methods

Case Conversion

text = "Hello, World!"

print(text.upper())      # HELLO, WORLD!
print(text.lower())      # hello, world!
print(text.title())      # Hello, World!
print(text.capitalize()) # Hello, world!
print(text.swapcase())   # hELLO, wORLD!

Searching and Checking

text = "Hello, World!"

# Find substring position
print(text.find("World"))    # 7
print(text.find("Python"))   # -1 (not found)
print(text.index("World"))   # 7 (raises error if not found)

# Check content
print(text.startswith("Hello"))  # True
print(text.endswith("!"))        # True
print("World" in text)           # True

# Character type checks
print("hello".isalpha())    # True
print("123".isdigit())      # True
print("hello123".isalnum()) # True
print("   ".isspace())      # True

Modifying Strings

text = "  Hello, World!  "

# Remove whitespace
print(text.strip())   # "Hello, World!"
print(text.lstrip())  # "Hello, World!  "
print(text.rstrip())  # "  Hello, World!"

# Replace
print(text.replace("World", "Python"))  # "  Hello, Python!  "

# Split and Join
words = "apple,banana,cherry".split(",")
print(words)  # ['apple', 'banana', 'cherry']

joined = "-".join(words)
print(joined)  # apple-banana-cherry

String Formatting

name = "Alice"
age = 30

# Basic formatting
print(f"Name: {name}, Age: {age}")

# Expressions
print(f"Next year: {age + 1}")

# Formatting numbers
price = 49.99
print(f"Price: ${price:.2f}")  # Price: $49.99

pi = 3.14159
print(f"Pi: {pi:.3f}")  # Pi: 3.142

# Padding and alignment
print(f"{'left':<10}|{'center':^10}|{'right':>10}")
# left      |  center  |     right

format() Method

# Positional arguments
print("{} and {}".format("Alice", "Bob"))  # Alice and Bob

# Named arguments
print("{name} is {age}".format(name="Alice", age=30))

# Number formatting
print("{:.2f}".format(3.14159))  # 3.14
print("{:,}".format(1000000))    # 1,000,000

String Operations

# Concatenation
greeting = "Hello" + " " + "World"
print(greeting)  # Hello World

# Repetition
echo = "Ha" * 3
print(echo)  # HaHaHa

# Length
print(len("Hello"))  # 5

# Count occurrences
text = "banana"
print(text.count("a"))  # 3

Working with Characters

# Convert to list of characters
text = "Hello"
chars = list(text)
print(chars)  # ['H', 'e', 'l', 'l', 'o']

# Iterate through characters
for char in "Hello":
    print(char, ord(char))  # Character and ASCII code

# Character from code
print(chr(65))  # A
print(chr(97))  # a

Practical Examples

# Clean and normalize input
user_input = "  JOHN DOE  "
clean_name = user_input.strip().title()
print(clean_name)  # John Doe

# Extract file extension
filename = "document.pdf"
extension = filename.split(".")[-1]
print(extension)  # pdf

# Check valid email (simple)
email = "user@example.com"
is_valid = "@" in email and "." in email
print(is_valid)  # True

# Create slug from title
title = "How to Use Python Strings!"
slug = title.lower().replace(" ", "-").replace("!", "")
print(slug)  # how-to-use-python-strings

Summary

  • Use indexing [i] and slicing [start:end:step] to access parts
  • Use .upper(), .lower(), .title() for case conversion
  • Use .strip(), .replace(), .split(), .join() for modification
  • Use f-strings for formatting: f"Value: {variable}"
  • Strings are immutable - methods return new strings