- Understand what strings are and how to create them
- Work with string indexing and slicing
- Understand string immutability
- Use escape characters and special strings
String Basics
Text is everywhere in programming. User names, messages, file contents, web pages – all text. In Python, we work with text using strings. Think of a string as a necklace of beads, where each bead is a character (letter, number, space, or symbol).
Strings are one of the most fundamental data types you'll use. Whether you're building a chatbot, processing user input, or reading files, you'll be working with strings constantly. Let's master them!
What is a String?
A string is an ordered sequence of characters:
String: "Hello"
Index: 0 1 2 3 4
Value: 'H' 'e' 'l' 'l' 'o'
Negative: -5 -4 -3 -2 -1
• Each character has a position (index)
• Indexing starts at 0
• Negative indices count from the end
Creating Strings
Python offers multiple ways to create strings:
Single and Double Quotes
# Both are equivalent
greeting = 'Hello, World!'
greeting = "Hello, World!"
# Use the other type when your string contains quotes
message = "It's a beautiful day!" # Contains single quote
quote = 'He said "Hello"' # Contains double quotes
# Or escape the quote
escaped = 'It\'s a beautiful day!' # \' escapes the quote
escaped = "He said \"Hello\"" # \" escapes the quote
Triple Quotes for Multi-line
# Triple quotes preserve line breaks
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you!"""
print(poem)
# Output:
# Roses are red,
# Violets are blue,
# Python is awesome,
# And so are you!
# Also great for docstrings
def greet():
"""This function greets the user.
It prints a friendly message.
"""
print("Hello!")
When to Use Which?
Quote Type Guide
SINGLE QUOTES ' '
• Quick, simple strings
• When string contains "double quotes"
• Example: name = 'Alice'
DOUBLE QUOTES " "
• When string contains 'apostrophes'
• Personal preference (many prefer these)
• Example: message = "It's working!"
TRIPLE QUOTES ''' ''' or """ """
• Multi-line strings
• Docstrings
• When string has both ' and "
• Example: long_text = """Line 1
Line 2"""
String Indexing
Access individual characters using their position:
text = "Python"
# Positive indexing (from start)
print(text[0]) # 'P' - first character
print(text[1]) # 'y' - second character
print(text[5]) # 'n' - sixth character
# Negative indexing (from end)
print(text[-1]) # 'n' - last character
print(text[-2]) # 'o' - second to last
print(text[-6]) # 'P' - first character (same as text[0])
Visual Index Map
Indexing "Python"
Positive: 0 1 2 3 4 5
Character: P y t h o n
Negative: -6 -5 -4 -3 -2 -1
text[0] → 'P' text[-1] → 'n'
text[2] → 't' text[-3] → 'h'
String Slicing
Extract a portion of a string:
text = "Hello, World!"
# Basic slicing: [start:end]
print(text[0:5]) # 'Hello' - characters 0 to 4 (end is exclusive!)
print(text[7:12]) # 'World'
# Omitting start or end
print(text[:5]) # 'Hello' - from beginning to index 4
print(text[7:]) # 'World!' - from index 7 to end
# Negative indices in slicing
print(text[-6:-1]) # 'World' - 6th from end to 1 before end
print(text[-6:]) # 'World!' - 6th from end to the end
# Step (every nth character)
print(text[::2]) # 'Hlo ol!' - every 2nd character
print(text[::-1]) # '!dlroW ,olleH' - reversed!
Slicing Syntax Explained
Slicing Syntax
string[start : end : step]
Jump by this many (default: 1)
Stop before this index
Begin at this index
Examples with "ABCDEFGH":
[2:6] → 'CDEF' (index 2 to 5)
[:4] → 'ABCD' (start to index 3)
[4:] → 'EFGH' (index 4 to end)
[::2] → 'ACEG' (every 2nd character)
[::-1] → 'HGFEDCBA' (reversed)
[1:6:2] → 'BDF' (index 1 to 5, every 2nd)
String Immutability
Strings cannot be changed after creation:
text = "Hello"
# THIS DOESN'T WORK - strings are immutable!
# text[0] = "J" # TypeError: 'str' does not support item assignment
# Create a NEW string instead
text = "J" + text[1:] # "Jello"
print(text)
# Or use string methods that return new strings
original = "hello"
uppercase = original.upper() # Creates new string "HELLO"
print(original) # Still "hello" - unchanged!
print(uppercase) # "HELLO"
Why Immutability?
Why Are Strings Immutable?
SAFETY: Multiple variables can share the same string
without worrying about unexpected changes
HASHABLE: Strings can be used as dictionary keys
because they never change
OPTIMIZATION: Python can reuse identical strings
in memory (string interning)
THREAD SAFE: No synchronization needed when sharing
strings between threads
Escape Characters
Special characters that have meaning beyond their appearance:
| Escape | Meaning | Example |
|---|---|---|
\n |
New line | "Line1\nLine2" |
\t |
Tab | "Col1\tCol2" |
\\ |
Backslash | "C:\\Users\\Name" |
\' |
Single quote | 'It\'s great' |
\" |
Double quote | "Say \"Hi\"" |
\r |
Carriage return | "Reset\rline" |
Examples
# Newline
print("Hello\nWorld")
# Output:
# Hello
# World
# Tab (for alignment)
print("Name\tAge\tCity")
print("Alice\t25\tParis")
# Output:
# Name Age City
# Alice 25 Paris
# Backslash (for file paths on Windows)
path = "C:\\Users\\Alice\\Documents"
print(path) # C:\Users\Alice\Documents
# Raw strings - ignores escape characters
raw_path = r"C:\Users\Alice\Documents"
print(raw_path) # C:\Users\Alice\Documents (same result, easier to read!)
String Operations
Length
text = "Hello, World!"
print(len(text)) # 13 (spaces and punctuation count!)
Concatenation (Joining)
first = "Hello"
last = "World"
# Using +
combined = first + " " + last # "Hello World"
# Using * for repetition
line = "-" * 20 # "--------------------"
echo = "Ha" * 3 # "HaHaHa"
Membership Testing
text = "Hello, World!"
print("World" in text) # True
print("world" in text) # False (case-sensitive!)
print("Python" in text) # False
print("xyz" not in text) # True
Practical Examples
Example 1: Extracting Information
email = "alice.smith@example.com"
# Get username (before @)
at_position = email.index("@")
username = email[:at_position]
print(f"Username: {username}") # alice.smith
# Get domain (after @)
domain = email[at_position + 1:]
print(f"Domain: {domain}") # example.com
Example 2: Simple Text Banner
def create_banner(text):
"""Create a text banner with decorative borders."""
width = len(text) + 4
border = "+" + "-" * (width - 2) + "+"
print(border)
print(f"| {text} |")
print(border)
create_banner("Welcome!")
# Output:
# +----------+
# | Welcome! |
# +----------+
Example 3: Password Masking
def mask_password(password):
"""Show only last 2 characters of password."""
if len(password) <= 2:
return "*" * len(password)
return "*" * (len(password) - 2) + password[-2:]
print(mask_password("secret123")) # *******23
print(mask_password("ab")) # **
Key Takeaways
Remember These Points
Strings are sequences of characters
Created with ' ', " ", or ''' '''
Indexing starts at 0
text[0] is first, text[-1] is last
Slicing: text[start:end:step]
End is exclusive! text[0:3] gets indices 0, 1, 2
Strings are IMMUTABLE
Can't change characters - create new strings
Escape characters: \n (newline), \t (tab), \\ (backslash)
Use raw strings r"..." to ignore escapes
len(text) gives length
+ concatenates, * repeats
What's Next?
You know the basics of strings – creating, indexing, and slicing. But the real power comes from string methods – built-in functions that let you search, transform, and analyze text. In the next lesson, we'll explore these powerful tools!
