Strings
Strings are one of Python's most used data types. They represent text and are immutable sequences of characters. This lesson covers creating strings, accessing characters, slicing, and formatting.
Creating Strings
Python strings can be created using single quotes, double quotes, or triple quotes for multiline strings. There's no difference between single and double quotes - use whichever is more convenient.
Click Run to execute your code
String Indexing
Every character in a string has a position called an index. Python uses zero-based indexing - the first character is at index 0. You can also use negative indices to count from the end.
Click Run to execute your code
-1 to get the last character without
knowing the string length. This is one of Python's most beloved features!
String Slicing
Slicing extracts a portion of a string using the syntax string[start:end:step].
The start index is included, but end is excluded.
Click Run to execute your code
[start:end] includes start but
excludes end. Think of indices as pointing between characters.
Escape Characters
Escape characters let you include special characters in strings. The backslash \
is the escape character.
| Escape | Description | Example |
|---|---|---|
\n | Newline | "Line1\nLine2" |
\t | Tab | "Col1\tCol2" |
\\ | Backslash | "C:\\path" |
\' | Single quote | 'It\'s' |
\" | Double quote | "Say \"Hi\"" |
\r | Carriage return | "Before\rAfter" |
Click Run to execute your code
r to create a raw string where
backslashes are treated literally. Perfect for file paths and regex patterns!
String Operations
Python provides operators for string concatenation, repetition, and membership testing.
Click Run to execute your code
String Formatting
Python offers several ways to format strings. f-strings (Python 3.6+) are the most modern and recommended approach.
Click Run to execute your code
.format() or the % operator.
Common Mistakes
1. Index out of range
text = "Hello"
print(text[5]) # IndexError! Valid indices are 0-4
print(text[4]) # Correct - gets 'o'
2. Trying to modify strings
text = "Hello"
text[0] = "J" # TypeError! Strings are immutable
# Do this instead:
text = "J" + text[1:] # Creates new string "Jello"
3. Concatenating strings with numbers
age = 25
# print("Age: " + age) # TypeError!
# Solutions:
print("Age: " + str(age)) # Convert to string
print(f"Age: {age}") # Use f-string (recommended)
4. Forgetting case sensitivity
text = "Python"
print("python" in text) # False! Case matters
print("python" in text.lower()) # True
Exercise: String Manipulation
Task: Practice string indexing, slicing, and operations with the given string.
Requirements:
- Extract specific characters using indexing
- Extract words using slicing
- Reverse the string
- Check for substring membership
- Create a pattern using repetition
Click Run to execute your code
Show Solution
text = "Learning Python is Fun!"
# 1. First character
print(text[0]) # 'L'
# 2. Last character
print(text[-1]) # '!'
# 3. Extract "Python"
print(text[9:15]) # 'Python'
# 4. Reverse the string
print(text[::-1]) # '!nuF si nohtyP gninraeL'
# 5. Check if "Python" is in text
print("Python" in text) # True
# 6. Length of string
print(len(text)) # 23
# 7. Every other character
print(text[::2]) # 'Lann yhn sFn'
# 8. Create pattern
print("=-" * 6 + "=") # '=-=-=-=-=-=-='
Summary
- Creation: Use single
'...', double"...", or triple"""..."""quotes - Indexing: Access characters with
string[index], starting at 0 - Negative indices:
-1is last character,-2is second-to-last - Slicing:
string[start:end:step]extracts substrings - Escape characters:
\n(newline),\t(tab),\\(backslash) - Raw strings: Prefix with
rto disable escape processing - f-strings: Use
f"..."for modern, readable formatting - Immutable: Strings cannot be changed - operations create new strings
What's Next?
In the next lesson, we'll explore string methods - powerful built-in functions for searching, transforming, and manipulating strings.
Enjoying these tutorials?