5 min read
Data Types II - Strings
Learn to work with text in Python
What You'll Learn
- What strings are
- Creating and using text
- Combining text
- Common text operations
What are Strings?
Strings are text. Anything inside quotes is a string:
code.py
name = "John"
message = 'Hello World'
address = "123 Main Street"Creating Strings
Use Single or Double Quotes
Both work the same:
code.py
name1 = "Sarah"
name2 = 'Mike'
print(name1) # Sarah
print(name2) # MikeLong Text (Multiple Lines)
Use triple quotes:
code.py
story = """
This is a long story.
It has multiple lines.
Python keeps them all!
"""
print(story)Combining Strings
Using + (Concatenation)
code.py
first_name = "John"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)
# Shows: John SmithCombining Text and Numbers
Convert numbers to strings first:
code.py
age = 25
message = "I am " + str(age) + " years old"
print(message)
# Shows: I am 25 years oldEasy Way (f-strings)
Put f before quotes and use {}:
code.py
name = "Sarah"
age = 28
message = f"My name is {name} and I am {age} years old"
print(message)
# Shows: My name is Sarah and I am 28 years oldString Operations
Length (How many characters)
code.py
name = "Python"
length = len(name)
print(length)
# Shows: 6Uppercase and Lowercase
code.py
text = "hello world"
uppercase = text.upper()
print(uppercase)
# Shows: HELLO WORLD
lowercase = text.lower()
print(lowercase)
# Shows: hello worldTitle Case (First Letter Capital)
code.py
name = "john smith"
title_name = name.title()
print(title_name)
# Shows: John SmithReplace Text
code.py
sentence = "I like cats"
new_sentence = sentence.replace("cats", "dogs")
print(new_sentence)
# Shows: I like dogsRemove Extra Spaces
code.py
text = " hello "
clean = text.strip()
print(clean)
# Shows: helloAccessing Parts of Strings
Each character has a position (starts at 0):
code.py
word = "Python"
first = word[0]
print(first)
# Shows: P
second = word[1]
print(second)
# Shows: y
last = word[-1]
print(last)
# Shows: nGet Multiple Characters
code.py
word = "Python"
first_three = word[0:3]
print(first_three)
# Shows: Pyt
last_three = word[-3:]
print(last_three)
# Shows: honPractice Examples
Example 1: Personal greeting
code.py
first_name = "Emma"
last_name = "Wilson"
age = 25
greeting = f"Hello! My name is {first_name} {last_name}."
info = f"I am {age} years old."
print(greeting)
print(info)Example 2: Email generator
code.py
name = "john smith"
domain = "gmail.com"
# Clean the name
clean_name = name.replace(" ", ".")
email = clean_name + "@" + domain
print(email)
# Shows: john.smith@gmail.comExample 3: Format names
code.py
name = "JOHN SMITH"
proper_name = name.title()
print(proper_name)
# Shows: John SmithChecking Text
Check if text is inside
code.py
sentence = "I love Python programming"
if "Python" in sentence:
print("Yes, Python is mentioned!")
# Shows: Yes, Python is mentioned!Check if starts with
code.py
email = "john@gmail.com"
if email.startswith("john"):
print("Email starts with john")Check if ends with
code.py
filename = "photo.jpg"
if filename.endswith(".jpg"):
print("This is a JPG image")Repeating Strings
Use * to repeat:
code.py
laugh = "ha" * 3
print(laugh)
# Shows: hahaha
line = "-" * 20
print(line)
# Shows: --------------------Common Mistakes
Mistake 1: Mixing quotes
code.py
text = "Hello' # Wrong!
text = "Hello" # Correct!Mistake 2: Forgetting to convert numbers
code.py
age = 25
text = "I am " + age # Error!
text = "I am " + str(age) # Correct!Mistake 3: Using quotes inside quotes
code.py
# Wrong way
text = "He said "Hi""
# Right way
text = "He said 'Hi'"
text = 'He said "Hi"'Quick Reference
code.py
len(text) # Length
text.upper() # UPPERCASE
text.lower() # lowercase
text.title() # Title Case
text.replace(old, new) # Replace text
text.strip() # Remove spaces
str(number) # Number to stringSummary
- Strings are text in quotes
- Use + to combine strings
- f-strings make combining easy:
f"Hello {name}" - Many useful operations: upper, lower, replace
- Access characters with [0], [1], etc.
- Convert numbers with str()
What's Next?
Now let's learn about True/False values (Booleans)!