Python — Strings
Creating strings
Python strings are delimited by single or double quotes — they're identical:
name = "Ada"
greeting = 'Hello'
Triple quotes handle multi-line strings:
poem = """
Roses are red,
Violets are blue,
Python is awesome,
And so are you.
"""
String indexing
Access individual characters by position (zero-indexed):
word = "Python"
print(word[0]) # P
print(word[5]) # n
print(word[-1]) # n (last character)
print(word[-2]) # o (second to last)
Negative indices count from the end — -1 is the last character.
Slicing
Extract substrings with the [start:stop:step] syntax:
text = "Hello, World!"
print(text[0:5]) # Hello (positions 0-4)
print(text[7:12]) # World
print(text[:5]) # Hello (start from beginning)
print(text[7:]) # World! (go to end)
print(text[::2]) "HloWrd (every other character)
print(text[::-1]) # !dlroW ,olleH (reversed)
Slicing never raises an index error — Python handles out-of-range gracefully.
String methods
text = " Hello, World! "
# Case methods
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
print(text.find("World")) # 9 (index of first occurrence)
print(text.find("Python")) # -1 (not found)
print(text.count("l")) # 3
print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
# Trimming
print(text.strip()) # "Hello, World!" — removes whitespace
print(text.lstrip()) # "Hello, World! " — left only
print(text.rstrip()) # " Hello, World!" — right only
# Replacing and splitting
print(text.replace("World", "Python")) # " Hello, Python! "
words = text.strip().split(", ") # ["Hello", "World!"]
String concatenation
first = "Hello"
second = "World"
combined = first + " " + second # "Hello World"
# Repetition
line = "-" * 30 # "------------------------------"
For building strings in loops, join() is more efficient:
words = ["Python", "is", "awesome"]
sentence = " ".join(words) # "Python is awesome"
csv = ",".join(words) # "Python,is,awesome"
f-strings — the modern way
f-strings embed expressions directly:
name = "Ada"
age = 36
score = 95.678
# Basic interpolation
print(f"Hello, {name}!")
# Expressions
print(f"Next year you'll be {age + 1}.")
# Format specifiers
print(f"Score: {score:.1f}") # 95.7
print(f"Score: {score:.0f}") # 96
print(f"Number: {42:05d}") # 00042
print(f"Price: ${19.99:.2f}") # $19.99
print(f"Percent: {0.856:.1%}") # 85.6%
print(f"Right-aligned: {42:>10}") # 42
print(f"Centered: {'hi':^10}") # hi
String methods for validation
text = "Hello123"
print(text.isalpha()) # False — contains digits
print(text.isalnum()) # True — letters and digits
print(text.isdigit()) # False — contains letters
print("12345".isdigit()) # True — all digits
print("hello".islower()) # True
print("HELLO".isupper()) # True
print("Hello".istitle()) # True — title case
print(" ".isspace()) # True — all whitespace
Raw strings
Prefix with r to treat backslashes as literal characters:
path = r"C:\Users\Ada\Documents"
print(path) # C:\Users\Ada\Documents
regex = r"\d+"
print(regex) # \d+ (not a digit pattern yet — just a string)
Raw strings are essential for Windows file paths and regular expressions.
String encoding
Python strings are Unicode by default:
text = "Hello, 世界!"
print(len(text)) # 10 — characters, not bytes
# Encode to bytes
encoded = text.encode("utf-8")
print(type(encoded)) # <class 'bytes'>
print(len(encoded)) # 14 — bytes needed
# Decode back to string
decoded = encoded.decode("utf-8")
print(decoded) # Hello, 世界!
Common string patterns
Checking substrings
email = "user@example.com"
if "@" in email and "." in email:
print("Looks like an email")
Formatting names
first = "Ada"
last = "Lovelace"
full = f"{first} {last}"
Building paths
import os
folder = "documents"
file = "report.pdf"
path = os.path.join(folder, file)
Strings are immutable
s = "Hello"
# s[0] = "h" # TypeError: 'str' object does not support item assignment
# Workaround — create a new string
s = "h" + s[1:] # "hello"
Every string method returns a new string. The original stays unchanged.
Mini Practice
- Reverse a string using slicing:
"Hello"→"olleH" - Count how many times a letter appears in a sentence
- Use f-strings to format a receipt with item names and prices
- Check if a string is a palindrome
- Split a sentence into words and rejoin them in reverse order
Next: operators — math and comparisons →
Related Topics
Frequently Asked Questions about Strings
What is Strings in Python?
Strings is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Strings?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.
Why is Strings important in Python?
Strings is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.