What is a String?
A string is a sequence of characters enclosed in quotes. Strings are immutable in Python, meaning you cannot change them after creation, but you can create new strings from existing ones.
Creating Strings
Create strings using single, double, or triple quotes:
# Single quotes
name = 'Alice'
# Double quotes
message = "Hello, World!"
# Triple quotes for multiline
text = """This is
a multiline
string"""
# Escape characters
quote = "She said, \"Hello\""
newline = "Line 1\nLine 2"
tab = "Column1\tColumn2"
String Operations
Concatenation
first = "Hello"
last = "World"
greeting = first + " " + last # "Hello World"
# Using join() for multiple strings
words = ["Hello", "World", "Python"]
sentence = " ".join(words) # "Hello World Python"
Repetition
word = "Hi"
repeated = word * 3 # "HiHiHi"
Length
text = "Python"
length = len(text) # 6
String Indexing and Slicing
Access individual characters or substrings:
text = "Python"
# Indexing (0-based)
first = text[0] # "P"
last = text[-1] # "n"
# Slicing
sub = text[0:3] # "Pyt" (from 0 to 2)
sub = text[:3] # "Pyt" (from start)
sub = text[3:] # "hon" (from 3 to end)
sub = text[::2] # "Pto" (every 2nd character)
sub = text[::-1] # "nohtyP" (reversed)
String Methods
Case Conversion
text = "Hello World"
upper_text = text.upper() # "HELLO WORLD"
lower_text = text.lower() # "hello world"
title_text = text.title() # "Hello World"
swap_text = text.swapcase() # "hELLO wORLD"
Searching and Checking
text = "Hello World"
# Check if starts/ends with
text.startswith("Hello") # True
text.endswith("World") # True
# Find substring
index = text.find("World") # 6 (returns -1 if not found)
index = text.index("World") # 6 (raises error if not found)
# Count occurrences
count = text.count("l") # 3
# Check content
text.isalpha() # False (has space)
text.isdigit() # False
text.isalnum() # False
Modifying Strings
text = " Hello World "
# Strip whitespace
cleaned = text.strip() # "Hello World"
left = text.lstrip() # "Hello World "
right = text.rstrip() # " Hello World"
# Replace
new_text = text.replace("World", "Python") # " Hello Python "
# Split
words = "apple,banana,orange".split(",") # ["apple", "banana", "orange"]
String Formatting
f-strings (Python 3.6+)
name = "Alice"
age = 25
# f-string (recommended)
message = f"My name is {name} and I'm {age} years old"
# Expressions
result = f"2 + 3 = {2 + 3}" # "2 + 3 = 5"
# Formatting numbers
price = 19.99
formatted = f"Price: ${price:.2f}" # "Price: $19.99"
format() Method
name = "Alice"
age = 25
message = "My name is {} and I'm {} years old".format(name, age)
message = "My name is {0} and I'm {1} years old".format(name, age)
message = "My name is {name} and I'm {age} years old".format(name=name, age=age)
% Formatting (Old Style)
name = "Alice"
age = 25
message = "My name is %s and I'm %d years old" % (name, age)
Common String Operations
Check if substring exists
text = "Hello World"
if "World" in text:
print("Found!")
Split and Join
# Split string into list
sentence = "apple,banana,orange"
fruits = sentence.split(",") # ["apple", "banana", "orange"]
# Join list into string
fruits = ["apple", "banana", "orange"]
sentence = ",".join(fruits) # "apple,banana,orange"
Remove whitespace
text = " Hello World "
cleaned = text.strip() # "Hello World"
String Immutability
Strings cannot be changed in place:
text = "Hello"
# text[0] = "h" # Error! Strings are immutable
# Create new string instead
new_text = "h" + text[1:] # "hello"
Raw Strings
Use raw strings to ignore escape characters:
# Regular string
path = "C:\\Users\\Name" # Need to escape backslashes
# Raw string
path = r"C:\Users\Name" # No escaping needed
Best Practices
- Use f-strings: Most readable and efficient (Python 3.6+)
- Use join() for concatenation: More efficient than + for multiple strings
- Be careful with string methods: They return new strings, don't modify in place
- Use strip() for user input: Remove unwanted whitespace
Next Steps
Learn about file handling to read and write strings to files, or explore regular expressions for advanced pattern matching.