Mingming Li — Click any blue heading below to expand the content.
A string is a sequence of characters used to represent text. In Python, you can create strings using single quotes ' ' or double quotes " ".
# String examples
name = "Alice"
message = 'Hello, World!'
empty = ""
quote = 'He said "Python is fun"'
multi_line = """This is
a multi-line
string"""
''' ''' or """ """ for multi-line strings.
# 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)
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"
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
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
# 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
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:
score?"Hello" + " " + "World" produce?text.upper() or "hello".upper()f"Score: {score}" or concatenation: "Score: " + str(score)Try these exercises to practice strings. Write your code in Thonny.
greeting = "hello world". Print it in uppercase, then in title case.text = " Python is awesome! " by removing extra spaces, then print its length.first = "John" and last = "Doe".C:\Users\Name\Desktop correctly."Score: " + str(score) or use f-string f"Score: {score}".text.upper() returns a new string. You need to assign it: text = text.upper().print(type(variable)) to check if a variable is a string. Use len(variable) to see its length before indexing.
s?s[-1] give you?s.find("x") and "x" in s?s[0] (indexing starts at 0)len(s)find() returns the index position (or -1 if not found); in returns True/False{variable}. They are cleaner and faster.