Python Strings · Working with Text

Mingming Li — Click any blue heading below to expand the content.

Table of Contents

1. What is a string?

A string is a sequence of characters used to represent text. In Python, you can create strings using single quotes ' ' or double quotes " ".

Think of a string as a necklace of letters, numbers, and symbols strung together in a specific order.
# String examples
name = "Alice"
message = 'Hello, World!'
empty = ""
quote = 'He said "Python is fun"'
multi_line = """This is
a multi-line
string"""
Quote rules: Use single quotes if your string contains double quotes, and vice versa. Use triple quotes ''' ''' or """ """ for multi-line strings.

2. Basic string operations

# Concatenation (joining strings)
first = "Hello"
last = "World"
greeting = first + " " + last   # "Hello World"

# Repetition
laugh = "ha" * 3   # "hahaha"

# Length (how many characters?)
text = "Python"
length = len(text)   # 6

# Access characters (indexing - starts at 0!)
text = "Python"
first_char = text[0]   # 'P'
second_char = text[1]  # 'y'
last_char = text[-1]   # 'n' (negative counts from the end)

# Slicing (getting a substring)
text = "Programming"
sub = text[0:4]    # "Prog" (from index 0 up to but not including 4)
sub2 = text[4:]    # "ramming" (from index 4 to the end)
sub3 = text[:4]    # "Prog" (from start to index 4)
Remember: In Python, indexing starts at 0, not 1! So text[0] is the first character.

3. Common string methods

text = "  Hello World  "

# Case conversion
text.upper()          # "  HELLO WORLD  "
text.lower()          # "  hello world  "
text.title()          # "  Hello World  "

# Removing whitespace (very useful for cleaning user input!)
text.strip()          # "Hello World"
text.lstrip()         # "Hello World  "
text.rstrip()         # "  Hello World"

# Finding and replacing
text.find("World")    # 9 (position where "World" starts)
text.replace("World", "Python")   # "  Hello Python  "

# Checking content (returns True/False)
text.isalpha()        # False (has spaces)
"abc123".isalnum()    # True (letters and numbers)
"123".isdigit()       # True
"abc".isalpha()       # True

# Splitting and joining (very useful!)
words = "apple,banana,cherry"
fruits = words.split(",")   # ['apple', 'banana', 'cherry'] (becomes a list)
joined = "-".join(fruits)   # "apple-banana-cherry"
Important: String methods do NOT change the original string. They return a NEW string. Strings are immutable (cannot be changed once created).

4. String formatting (f-strings)

f-strings (Python 3.6+) are the easiest way to insert variables into strings. Just put an f before the quotes and use {variable}.

name = "Alice"
age = 25
score = 95.5

# f-string examples
message = f"My name is {name} and I am {age} years old."
print(message)   # "My name is Alice and I am 25 years old."

# You can also do calculations inside {}
print(f"Next year I will be {age + 1}.")
print(f"In 10 years, I will be {age + 10}.")

# Format numbers (control decimal places)
print(f"Your score is {score:.1f}")   # "Your score is 95.5"
print(f"Your score is {score:.0f}")   # "Your score is 96" (rounded)
print(f"Percentage: {score/100:.0%}") # "Percentage: 96%"

# Align text
print(f"{'left':<10}")   # left aligned
print(f"{'right':>10}")  # right aligned
print(f"{'center':^10}") # center aligned
Why use f-strings? They are faster, cleaner, and easier to read than older formatting methods. Always use f-strings for new code!

5. Escape characters

Escape characters allow you to include special characters that would otherwise be hard to type.

# Common escape sequences
newline = "Line1\nLine2"      # \n = new line (line break)
tab = "Column1\tColumn2"      # \t = tab (indent)
backslash = "Path\\to\\file"  # \\ = backslash
single_quote = 'It\'s nice'   # \' = single quote inside single quotes
double_quote = "She said \"Hi\""  # \" = double quote inside double quotes

print("Hello\nWorld")
# Output:
# Hello
# World

# Raw strings (ignore escape characters - great for file paths!)
path = r"C:\Users\Name\Documents"
print(path)   # prints exactly as written, no escape issues
Pro tip: When working with Windows file paths, use raw strings (r"path") to avoid escape sequence problems!

6. Quick reference

# CREATING STRINGS
s1 = 'single quotes'
s2 = "double quotes"
s3 = '''multi-line
string'''
s4 = r"raw\string"

# COMMON OPERATIONS
len(s)              # length
s + t               # concatenation (join)
s * 3               # repetition
s[i]                # indexing (0-based)
s[-1]               # last character
s[i:j]              # slicing (from i to j-1)
s[i:j:k]            # slicing with step

# USEFUL METHODS
s.upper()           # all uppercase
s.lower()           # all lowercase
s.strip()           # remove whitespace from ends
s.replace(old, new) # replace substring
s.split(sep)        # split into list
sep.join(list)      # join list into string
s.find(sub)         # find position (returns -1 if not found)
sub in s            # check if contains (returns True/False)

# F-STRING FORMATTING
f"value is {var}"
f"{var:.2f}"        # 2 decimal places
f"{var:>10}"        # right align width 10
f"{var:<10}"        # left align width 10
f"{var:^10}"        # center align width 10

7. Quick Challenge: String Detective

Look at this code from our game. Can you find the strings?

# Game over screen
font = pygame.font.Font(None, 36)
text = font.render("Press SPACE to start", True, (100, 100, 255))
text_rect = text.get_rect(center=(400, 200))
screen.blit(text, text_rect)

# Player name (if we added one)
player_name = "Mingming"
score_text = f"Score: {score}"

Questions:

  1. What are the string literals in this code?
  2. What string method would you use to make "hello" into "HELLO"?
  3. How would you combine "Score: " and the variable score?
  4. What does "Hello" + " " + "World" produce?
Click for answers
  1. "Press SPACE to start", "Mingming", "Score: "
  2. text.upper() or "hello".upper()
  3. f-string: f"Score: {score}" or concatenation: "Score: " + str(score)
  4. "Hello World"

8. Exercises

Try these exercises to practice strings. Write your code in Thonny.

  • Exercise 1: Create greeting = "hello world". Print it in uppercase, then in title case.
  • Exercise 2: Clean text = " Python is awesome! " by removing extra spaces, then print its length.
  • Exercise 3: Use f-strings to create "My name is John Doe" from first = "John" and last = "Doe".
  • Exercise 4: Find the position of "fox" in "The quick brown fox jumps over the lazy dog".
  • Exercise 5: Replace all vowels in "Hello World" with '*'.
  • Exercise 6: Use a raw string to print the path C:\Users\Name\Desktop correctly.
  • Exercise 7: Split "apple,banana,cherry,date" into a list, then join with '-'.
  • Exercise 8: Ask user for first and last name, then print "Hello, [first] [last]! Welcome to Python."
  • Exercise 9: Extract from "abcdefghijk": (a) first 3 chars, (b) last 3 chars, (c) every other char.
  • Exercise 10: Check if a word is a palindrome (same forwards and backwards, like "racecar").
  • Exercise 11: Extract username and domain from "user@example.com".
  • Exercise 12: Print "Python" in reverse using slicing.

9. Common Errors & Solutions

  • TypeError: can only concatenate str (not "int") to str
    -> You tried to add a number to a string. Fix: "Score: " + str(score) or use f-string f"Score: {score}".
  • IndexError: string index out of range
    -> You tried to access a character at an index that doesn't exist. Remember indexing starts at 0 and goes to len(s)-1.
  • SyntaxError: EOL while scanning string literal
    -> You forgot to close a quote. Check that every opening quote has a matching closing quote.
  • AttributeError: 'int' object has no attribute 'upper'
    -> You tried to use a string method on a number. Make sure your variable is a string.
  • String is immutable (doesn't change after method call)
    -> text.upper() returns a new string. You need to assign it: text = text.upper().
Debugging tip: Use print(type(variable)) to check if a variable is a string. Use len(variable) to see its length before indexing.

10. Check Your Understanding

  1. How do you get the first character of a string s?
  2. What does s[-1] give you?
  3. How do you get the length of a string?
  4. What is the difference between s.find("x") and "x" in s?
  5. Why are strings called "immutable"?
  6. What is an f-string and why is it useful?
Click for Answers
  1. s[0] (indexing starts at 0)
  2. The last character of the string
  3. len(s)
  4. find() returns the index position (or -1 if not found); in returns True/False
  5. Strings cannot be changed after creation. Methods return NEW strings.
  6. f-strings let you insert variables directly into strings using {variable}. They are cleaner and faster.

11. Your Progress Tracker

Check off each item as you master it:
I can create strings using quotes
I can concatenate strings with + and *
I can access characters using indexing (s[0], s[-1])
I can extract substrings using slicing
I can use len() to get string length
I can use upper(), lower(), strip(), replace()
I can split strings into lists and join lists into strings
I can use f-strings to format text
I understand escape characters and raw strings
I completed at least 8 exercises