- What are strings — understanding text data in Python
- Creating strings — using quotes and different methods
- String indexing — accessing individual characters
- String slicing — extracting portions of text
- String operations — concatenation, repetition, and more
- Immutability — why strings can't be changed in place
What Are Strings?
In Python, a string is simply a piece of text. It could be a single letter, a word, a sentence, or even an entire book. Strings are how we work with text in programming — from user input to file content to API responses.
Think of a string like a necklace made of beads. Each bead is a character — a letter, number, space, or symbol. The whole necklace is the string, and the beads are in a specific order. Python gives you tools to examine, rearrange, and work with these beads.
💡 Key concept: Strings are one of the most important data types in Python. Almost every program you write will use strings in some way — for output, user input, data processing, and much more.
Creating Strings
Ways to Create Strings
# Strings can be created in several ways
# 1. Using single quotes
name = 'Alice'
greeting = 'Hello, World!'
print(greeting) # Hello, World!
# 2. Using double quotes
message = "Python is awesome"
print(message) # Python is awesome
# 3. Single quotes vs double quotes
# You can use either, but be consistent
# Use double quotes when your string contains single quotes:
text = "It's a beautiful day"
print(text) # It's a beautiful day
# Use single quotes when your string contains double quotes:
quote = 'She said, "Hello!"'
print(quote) # She said, "Hello!"
# 4. Triple quotes for multi-line strings
long_text = """This is a multi-line string.
It can span multiple lines.
You can write paragraphs in it."""
print(long_text)
# 5. Triple quotes with single quotes work too
another_text = '''This is also a multi-line string.
It works the same way.'''
# 6. Creating empty strings
empty1 = ''
empty2 = ""
empty3 = str() # Using the str() function
print(empty1) # (nothing prints)
# 7. Converting other types to strings
age = 25
age_str = str(age)
print(f"Age as string: {age_str}")
print(f"Type: {type(age_str)}")
Creating strings key points:
- Quotes — single, double, or triple for multi-line
- Consistency — pick a style and stick with it
- str() — convert numbers and other types to strings
- Empty strings — useful as placeholders
Quick Check: What type of quotes would you use for a multi-line string? (Answer: Triple quotes)
String Indexing
Accessing Individual Characters
# Each character in a string has an index (position)
word = "Python"
# 1. Positive indexing (starts from 0)
print(word[0]) # P
print(word[1]) # y
print(word[2]) # t
print(word[3]) # h
print(word[4]) # o
print(word[5]) # n
# 2. Negative indexing (starts from -1 from the end)
print(word[-1]) # n
print(word[-2]) # o
print(word[-3]) # h
print(word[-4]) # t
print(word[-5]) # y
print(word[-6]) # P
# 3. Getting the length of a string
length = len(word)
print(f"Length of '{word}': {length}") # 6
# 4. Accessing the last character
last_char = word[-1] # or word[len(word)-1]
print(f"Last character: {last_char}")
# 5. Trying to access an index that doesn't exist
# print(word[10]) # This will cause an IndexError
# 6. Strings are sequences - you can check if a character exists
if 'P' in word:
print("'P' is in the string")
Indexing key points:
- Positive indices — start at 0 for the first character
- Negative indices — start at -1 for the last character
- len() — get the number of characters
- IndexError — happens when you access an index that doesn't exist
Quick Check: What is the index of the first character in a string? (Answer: 0)
String Slicing
Extracting Parts of a String
# Slicing lets you extract a portion of a string
# Syntax: string[start:end:step]
text = "Python Programming"
# 1. Basic slicing
print(text[0:6]) # Python (characters from index 0 to 5)
print(text[7:18]) # Programming (index 7 to 17)
print(text[:6]) # Python (from beginning to index 5)
print(text[7:]) # Programming (from index 7 to end)
print(text[:]) # Python Programming (entire string)
# 2. Slicing with negative indices
print(text[-11:]) # Programming (from -11 to end)
print(text[-6:-1]) # rammi (last 5 characters except the last)
# 3. Slicing with step
word = "abcdefghij"
print(word[::2]) # acegi (every second character)
print(word[1::2]) # bdfhj (every second character starting from index 1)
print(word[::-1]) # jihgfedcba (reverses the string)
# 4. Practical examples
name = "Alice Johnson"
first_name = name[:5]
last_name = name[6:]
print(f"First name: {first_name}") # Alice
print(f"Last name: {last_name}") # Johnson
# 5. Slicing to get a substring
email = "user@example.com"
username = email[:email.index('@')]
domain = email[email.index('@')+1:]
print(f"Username: {username}") # user
print(f"Domain: {domain}") # example.com
Slicing key points:
- Start — the index to begin (inclusive)
- End — the index to stop (exclusive)
- Step — how many characters to skip
- Negative step — reverses the string
- Omitted values — default to beginning, end, or 1
Quick Check: How do you reverse a string using slicing? (Answer: string[::-1])
String Concatenation
Joining Strings Together
# Concatenation means joining strings together
# 1. Using the + operator
first_name = "Alice"
last_name = "Johnson"
full_name = first_name + " " + last_name
print(full_name) # Alice Johnson
# 2. Joining multiple strings
greeting = "Hello"
name = "Bob"
message = greeting + ", " + name + "!"
print(message) # Hello, Bob!
# 3. Concatenating string literals
# Python automatically concatenates adjacent string literals
text = "Hello" " " "World"
print(text) # Hello World
# 4. Using join() method (more efficient for many strings)
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Python is awesome
# 5. Concatenating numbers (must convert to string first)
age = 25
message = "I am " + str(age) + " years old"
print(message) # I am 25 years old
# 6. Using f-strings (Python 3.6+)
name = "Charlie"
age = 30
message = f"{name} is {age} years old"
print(message) # Charlie is 30 years old
Concatenation key points:
- + operator — join strings together
- join() — efficient for joining many strings
- str() — convert numbers to strings
- f-strings — modern and readable
Quick Check: Which method is more efficient for joining many strings? (Answer: join())
String Repetition
Repeating Strings
# The * operator repeats strings
# 1. Basic repetition
text = "Ha"
print(text * 3) # HaHaHa
# 2. Creating a line
line = "-" * 40
print(line)
print("Header")
print(line)
# 3. Creating a pattern
pattern = "* " * 10
print(pattern) # * * * * * * * * * *
# 4. Repeating with variables
count = 5
print("Hello " * count) # Hello Hello Hello Hello Hello
# 5. Repeating zero times gives an empty string
print("Test" * 0) # (nothing prints)
# 6. Repeating with user input
# num = int(input("How many times? "))
# print("Yes! " * num)
# 7. Creating a simple progress bar
def progress_bar(percentage):
filled = "█" * (percentage // 10)
empty = "░" * (10 - (percentage // 10))
return f"{filled}{empty} {percentage}%"
print(progress_bar(30)) # ███░░░░░░░ 30%
print(progress_bar(75)) # ███████░░░ 75%
Repetition key points:
- * operator — repeats a string
- Integer value — must be a whole number
- Zero repetitions — gives an empty string
- Useful for — creating lines, patterns, progress bars
Quick Check: What operator is used to repeat a string? (Answer: *)
String Immutability
Why Strings Can't Be Changed In Place
# Strings in Python are immutable — they cannot be changed after creation
text = "Hello"
# 1. Trying to change a character directly (this doesn't work)
# text[0] = "J" # This will cause a TypeError
# 2. Instead, you create a new string
new_text = "J" + text[1:]
print(new_text) # Jello
# 3. Converting to a list (mutable), changing, then back to string
text_list = list("Hello")
text_list[0] = "J"
new_text = "".join(text_list)
print(new_text) # Jello
# 4. Many string methods return new strings
original = "python"
upper_version = original.upper()
print(original) # python (unchanged)
print(upper_version) # PYTHON (new string)
# 5. Memory efficiency
# Python reuses strings when possible
a = "hello"
b = "hello"
print(a is b) # True (same object in memory)
# 6. Each modification creates a new string
text = "Hello"
text = text + " World" # Creates a new string, old one is garbage collected
Immutability key points:
- Cannot change in place — strings are read-only after creation
- New strings — operations create new strings
- Memory efficient — Python reuses string objects when possible
- List conversion — convert to list for modifications
Quick Check: Can you change a string after it's created? (Answer: No, strings are immutable)
Escape Sequences
Special Characters in Strings
# Escape sequences let you include special characters in strings
# 1. Newline (\n)
print("Hello\nWorld")
# Hello
# World
# 2. Tab (\t)
print("Name:\tAlice")
print("Age:\t25")
# Name: Alice
# Age: 25
# 3. Backslash (\\)
print("C:\\Users\\Documents")
# C:\Users\Documents
# 4. Single quote (\')
print("It\'s a beautiful day")
# It's a beautiful day
# 5. Double quote (\")
print("She said, \"Hello!\"")
# She said, "Hello!"
# 6. Raw strings (ignore escape sequences)
path = r"C:\Users\Documents\file.txt"
print(path) # C:\Users\Documents\file.txt
# 7. Unicode characters
print("\u263A") # ☺
print("\u2764") # ❤
# 8. Combining escape sequences
print("Line1\nLine2\nLine3")
print("Column1\tColumn2\tColumn3")
Escape sequences key points:
- \n — new line
- \t — tab
- \\ — backslash
- \' — single quote
- \" — double quote
- r"..." — raw strings ignore escapes
Quick Check: What escape sequence creates a new line? (Answer: \n)
Try It Yourself
Experiment with strings in the editor below. Try creating, indexing, and slicing strings.
STRINGS BASICS PRACTICE
========================================
1. CREATING STRINGS
Hello, World!
Alice
2. STRING INDEXING
First character: P
Last character: n
Length: 6
3. STRING SLICING
First 4 characters: Prog
Last 4 characters: ming
Every second character: Pormn
Reversed: gnimmargorP
4. STRING CONCATENATION
Full name: John Doe
5. STRING REPETITION
--------------------
PythonPythonPython
6. ESCAPE SEQUENCES
Line 1
Line 2
Column 1 Column 2
Strings basics practice complete!
You've Got It!
You now understand the basics of strings in Python — creating them, accessing characters, slicing, and common operations. This is the foundation for all string work!
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between single and double quotes?
What is the difference between indexing and slicing?
Why are strings immutable in Python?
What's a common interview question about strings?
Can I use spaces in strings?
How do I convert a number to a string?
str() function: age_str = str(25). This converts any number to its string representation so you can concatenate it with other strings.
Where to Go From Here
Now that you understand string basics, check out these related topics:
String Special Operators
Learn about operators like %, in, and more for strings.
Learn More →String Formatting
Master different ways to format strings in Python.
Learn More →String Methods
Explore Python's powerful string methods.
Learn More →