Quiz 2

Strings — Basics & Operations

2065 words
10 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Strings — Basics & Operations > **Why read this?** Text processing is one of the most common programming tasks — reading names, parsing documents, validating input, generating reports. Strings are how Python handles text, and mastering them is essential for almost everything you'll write.

Strings — Basics & Operations

Why read this? Text processing is one of the most common programming tasks — reading names, parsing documents, validating input, generating reports. Strings are how Python handles text, and mastering them is essential for almost everything you'll write.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Create strings with single, double, and triple quotes
  2. Access individual characters using indexing (positive and negative)
  3. Extract substrings using slicing with start, stop, and step
  4. Use common string methods: upper(), lower(), strip(), replace(), find()
  5. Understand string immutability and its implications

📋 Prerequisites


📖 Core Content

5.1 What Problem Do Strings Solve?

Intuition: Computers store text as sequences of characters. A string is Python's way of representing and manipulating text. Whether it's a user's name, a paragraph, or the entire text of a book — it's all strings.

5.2 Creating Strings

python
# runnable
# Single quotes
s1 = 'Hello'
print(s1)
# Double quotes (most common)
s2 = "World"
print(s2)
# Triple quotes (multi-line strings)
s3 = """This is a
multi-line
string!"""
print(s3)
# Triple quotes with single quotes too
s4 = '''This also
works'''
print(s4)
Output:
pseudo
Hello
World
This is a
multi-line
string!
This also
works
Why multiple quote types? They let you include quotes inside strings without escaping:
python
print("It's a sunny day")     # Double-quoted string containing apostrophe
print('She said "Hello"')     # Single-quoted string containing double quotes

5.3 String Indexing — Getting Individual Characters

Every character in a string has a position (index). Python uses zero-based indexing: the first character is at index 0.
python
# runnable
word = "Python"
#       012345   (positive indices)
#      -6-5-4-3-2-1   (negative indices)
print(word[0])    # P (first character)
print(word[1])    # y (second character)
print(word[5])    # n (sixth character)
print(word[-1])   # n (last character)
print(word[-2])   # o (second-to-last)
print(word[-6])   # P (first character, using negative)
Output:
pseudo
P
y
n
n
o
P
Mental model: (Diagram)

5.4 String Slicing — Extracting Substrings

Syntax: string[start:stop:step]
  • start: Where to begin (inclusive). Default: beginning.
  • stop: Where to end (exclusive — the character at stop is NOT included). Default: end.
  • step: How many characters to skip. Default: 1.
python
# runnable
word = "Python Programming"
# Basic slicing
print(word[0:6])       # "Python"  (characters 0 to 5)
print(word[7:18])      # "Programming" (characters 7 to 17)
print(word[:6])        # "Python"  (from start to index 6)
print(word[7:])        # "Programming" (from index 7 to end)
print(word[:])         # "Python Programming" (entire string)
print(word[-11:])      # "Programming" (using negative index)
# With step
print(word[0:6:2])     # "Pto"  (index 0, 2, 4)
print(word[::-1])      # "gnimmargorP nohtyP" (reversed!)
print(word[::2])       # "Pto rgamn" (every other character)
Output:
pseudo
Python
Programming
Python
Programming
Python Programming
Programming
Pto
gnimmargorP nohtyP
Pto rgamn
Visualizing slices:
text
Index:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17
        P  y  t  h  o  n     P  r  o  g  r  a  m  m  i  n  g
       [0:6] → Python
       [7: ] → Programming
       [   :6] → Python
       [   : :2] → P t o   r g a m n

5.5 Slicing Rules and Edge Cases

python
# runnable
text = "Python"
# start beyond end returns empty string
print(text[10:15])     # "" (empty)
# stop before start returns empty
print(text[4:1])       # "" (empty)
# Negative step naturally reverses
print(text[4:1:-1])    # "oht" (indices 4,3,2)
# Omitting both with step -1 reverses
print(text[::-1])      # "nohtyP"
Output:
pseudo
                     (empty line)
                     (empty line)
oht
nohtyP

5.6 Strings Are Immutable

Critical concept: Once created, a string cannot be changed. You cannot modify a character in place.
python
# runnable
word = "Python"
# word[0] = "J"   # This would cause an error!
# Instead, create a NEW string:
new_word = "J" + word[1:]
print(new_word)      # "Jython"
Why immutability matters: It makes strings safe to share across functions, enables efficient hashing (for dictionary keys), and prevents accidental changes.

5.7 Common String Methods

Python provides many built-in methods that return NEW strings (remember: originals can't change):
python
# runnable
text = "  Hello, Python World!  "
print(text.upper())           # "  HELLO, PYTHON WORLD!  "
print(text.lower())           # "  hello, python world!  "
print(text.strip())           # "Hello, Python World!" (removes leading/trailing spaces)
print(text.replace("World", "Universe"))  # "  Hello, Python Universe!  "
print(text.find("Python"))    # 9 (index where "Python" starts)
print(text.find("Java"))      # -1 (not found)
print(text.count("o"))        # 3 (how many times 'o' appears)
print(text.startswith("  He")) # True
print(text.endswith("!  "))   # True
Output:
pseudo
  HELLO, PYTHON WORLD!
  hello, python world!
Hello, Python World!
  Hello, Python Universe!
9
-1
3
True
True

5.8 The len() Function

len() returns the number of characters in a string:
python
# runnable
word = "Python"
print(len(word))          # 6
sentence = "Hello World"
print(len(sentence))      # 11 (includes the space)
empty = ""
print(len(empty))         # 0
Output:
pseudo
6
11
0

5.9 String Concatenation and Repetition

python
# runnable
# Concatenation (joining)
first = "Hello"
second = "World"
message = first + " " + second
print(message)            # "Hello World"
# Repetition
laugh = "Ha" * 3
print(laugh)              # "HaHaHa"
# Useful for separators
print("=" * 30)           # "=============================="
Output:
pseudo
Hello World
HaHaHa
==============================

5.10 Worked Example 1: Name Formatter

python
# runnable
name = input("Enter your full name: ")
# Clean up extra spaces
name = name.strip()
# Find the space
space_index = name.find(" ")
first_name = name[:space_index]
last_name = name[space_index + 1:]
print(f"First name: {first_name}")
print(f"Last name: {last_name}")
print(f"Initials: {first_name[0]}.{last_name[0]}.")
print(f"Name capitalized: {name.title()}")
Output (user types " alice smith "):
pseudo
Enter your full name:   alice smith
First name: alice
Last name: smith
Initials: a.s.
Name capitalized: Alice Smith

5.11 Worked Example 2: Palindrome Checker

A palindrome reads the same forwards and backwards (e.g., "racecar", "madam").
python
# runnable
word = input("Enter a word: ").strip().lower()
reversed_word = word[::-1]
if word == reversed_word:
    print(f"'{word}' is a palindrome!")
else:
    print(f"'{word}' is NOT a palindrome.")
    print(f"Reversed: {reversed_word}")
Output:
pseudo
Enter a word: Racecar
'racecar' is a palindrome!

5.12 Worked Example 3: Counting Vowels

python
# runnable
text = input("Enter text: ").lower()
vowels = "aeiou"
count = 0
for ch in text:
    if ch in vowels:
        count += 1
print(f"Number of vowels: {count}")
Output:
pseudo
Enter text: Beautiful Python
Number of vowels: 7

5.13 Worked Example 4: Email Extractor

python
# runnable
email = "  [email protected]  "
email = email.strip()
# Find @ position
at_pos = email.find("@")
username = email[:at_pos]
domain = email[at_pos + 1:]
print(f"Email: {email}")
print(f"Username: {username}")
print(f"Domain: {domain}")
# Extract top-level domain
dot_pos = domain.rfind(".")
tld = domain[dot_pos + 1:]
print(f"TLD: {tld}")
Output:
pseudo
Email: user@example.com
Username: user
Domain: example.com
TLD: com

5.14 Worked Example 5: Caesar Cipher (Simple Encryption)

python
# runnable
text = input("Enter text: ").upper()
shift = int(input("Shift amount: "))
result = ""
for ch in text:
    if ch.isalpha():
        # Shift character, wrapping around alphabet
        new_pos = (ord(ch) - ord('A') + shift) % 26
        result += chr(ord('A') + new_pos)
    else:
        result += ch
print(f"Encrypted: {result}")
Output:
pseudo
Enter text: Hello World
Shift amount: 3
Encrypted: KHOOR ZRUOG

📐 Key Concepts Reference

OperationSyntaxExampleResult
Indexings[i]"Python"[0]"P"
Negative indexs[-i]"Python"[-1]"n"
Slices[start:stop]"Python"[0:3]"Pyt"
Slice with steps[start:stop:step]"Python"[::2]"Pto"
Reverses[::-1]"Python"[::-1]"nohtyP"
Lengthlen(s)len("Python")6
Concatenates1 + s2"Py" + "thon""Python"
Repeats * n"Hi" * 3"HiHiHi"
Uppercases.upper()"Hi".upper()"HI"
Lowercases.lower()"Hi".lower()"hi"
Strips.strip()" Hi ".strip()"Hi"
Finds.find(sub)"Hi".find("i")1
Replaces.replace(old, new)"Hi".replace("i","o")"Ho"

⚠️ Common Pitfalls

Pitfall 1: Index Out of Range

The mistake: "Python"[10] The error: IndexError: string index out of range Why: The string only has 6 characters (indices 0-5). You tried to access index 10. Fix: Always check len(string) before accessing an index, or use slicing (which handles out-of-range gracefully).

Pitfall 2: Forgetting Strings Are Immutable

The mistake: s = "Hello"; s[0] = "J" The error: TypeError: 'str' object does not support item assignment Why: Strings can't be changed in place. You must create a new string. Fix: s = "J" + s[1:] creates a new string "Jello".

Pitfall 3: Confusing find() Return Value with Boolean

The mistake: if "Python".find("xyz"): — this is False when find returns 0! Why: find() returns -1 if not found, but returns 0 if found at position 0. Since 0 is falsy, if s.find("abc"): would be False even if "abc" starts at position 0. Fix: Use if "xyz" in s: for membership, or if s.find("abc") != -1:.

Pitfall 4: Slicing Stop Value Is Exclusive

The mistake: "Python"[0:5] expecting "Pytho" (indices 0,1,2,3,4) — but the actual result IS "Pytho". The confusion comes from thinking index 5 is included. Remember: s[start:stop] includes indices up to (but not including) stop. So s[0:5] gives indices 0,1,2,3,4 (5 characters).

📝 Practice Questions

Q1: What is the output?
python
text = "Programming"
print(text[0:6])
print(text[-7:])
Answer:
pseudo
Progra
amming
  • text[0:6] → indices 0,1,2,3,4,5 → "Progra"
  • text[-7:] → last 7 characters → "amming" Q2: What does this return?
python
"Python"[::-1]
Answer:
pseudo
"nohtyP"
The [::-1] slice means: start at the end, go backwards by 1 step, so the entire string is reversed. Q3: Why does this code fail? Fix it.
python
name = "Alice"
name[0] = "B"
Answer: Error: TypeError: 'str' object does not support item assignment Why: Strings are immutable — you can't change a character in place. Fix: name = "B" + name[1:] → "Blice" Q4: What does this output?
python
s = "Hello World"
print(s.find("o"))
print(s.find("o", 5))
print(s.rfind("o"))
Answer:
pseudo
4
7
7
  • s.find("o") — finds first 'o' at index 4
  • s.find("o", 5) — starts searching from index 5, finds 'o' at index 7
  • s.rfind("o") — reverse find, finds last 'o' at index 7 Q5: Write code to extract the file extension from a filename like "document.pdf".
Answer:
python
# runnable
filename = "document.pdf"
dot_pos = filename.find(".")
extension = filename[dot_pos + 1:]
print(f"Extension: {extension}")

# For multiple dots (e.g., "my.file.name.txt"):
ext = filename.split(".")[-1]  # we'll learn split() later
print(f"Extension: {ext}")
Q6: What is the output of this code?
python
text = "  spaces  "
print(text.strip())
print(text.lstrip())
print(text.rstrip())
Answer:
pseudo
spaces
spaces
  spaces
  • strip() removes leading AND trailing spaces
  • lstrip() removes only leading (left) spaces
  • rstrip() removes only trailing (right) spaces Q7: What does len("") return?
Answer: 0
An empty string has no characters, so its length is 0. Q8: Write code to check if a string starts with a vowel.
Answer:
python
# runnable
word = input("Enter a word: ").strip().lower()
if word[0] in "aeiou":
    print(f"'{word}' starts with a vowel.")
else:
    print(f"'{word}' starts with a consonant.")
Q9: What is the output?
python
s = "abracadabra"
print(s.count("a"))
print(s.replace("a", "o"))
Answer:
pseudo
5
obrocodobro
  • count("a") counts how many times 'a' appears → 5
  • replace("a", "o") replaces ALL occurrences of 'a' with 'o' Q10: Write code to reverse each word in a two-word string.
Answer:
python
# runnable
text = "Hello World"
space_pos = text.find(" ")
first = text[:space_pos]
second = text[space_pos + 1:]
reversed_text = first[::-1] + " " + second[::-1]
print(reversed_text)  # "olleH dlroW"

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.