Python Strings: Create, Access, Slice, and Manipulate Text
Think about your phone. Almost everything you see on the screen is text: names in your contacts, messages from friends, search results, notifications. Behind the scenes, all of that text is handled by strings.
A string is how Python stores and works with text. It could be a single letter, a full sentence, or even an entire book. If it's text, it's a string.
In this tutorial, you'll learn how to create strings, pull out specific characters, slice strings apart, glue them together, and check what's inside them. These are skills you'll use in almost every Python program you write.
What Are Strings in Python?
A string is a sequence of characters wrapped in quotes. You can use single quotes, double quotes, or triple quotes. Python treats them all as strings.
Think of a string like a necklace of beads. Each bead is one character. The quotes are the clasp that holds the necklace together.
Single and double quotes work exactly the same way. The main reason to have both is convenience: if your text contains one type of quote, you can wrap it in the other.
Even an empty pair of quotes creates a string. An empty string has zero characters but is still a valid string.
How Do You Access Individual Characters in a String?
Every character in a string has a position number called an index. You can grab any character by putting its index inside square brackets.
Here's the important part: Python starts counting at 0, not 1. The first character is at index 0, the second is at index 1, and so on. This is called zero-based indexing.
Think of string indices like house numbers on a street. The first house is number 0, not number 1. It feels weird at first, but you'll get used to it fast.
What Are Negative Indices in Python?
Python also lets you count backwards from the end using negative indices. The last character is at index -1, the second-to-last is -2, and so on.
How Does String Slicing Work in Python?
Indexing grabs one character. Slicing grabs a chunk of characters. It's like cutting a piece from the middle of a loaf of bread.
The syntax is string[start:stop]. It grabs characters from start up to (but not including) stop. This "up to but not including" rule is one of the most important things to remember.
You can leave out the start or the stop. If you skip the start, Python begins at the beginning. If you skip the stop, Python goes all the way to the end.
How Does the Step Parameter Work in Slicing?
There's a third number you can add: string[start:stop:step]. The step controls how many characters to skip. A step of 2 grabs every other character.
The most famous use of the step parameter is reversing a string. A step of -1 walks backwards through the entire string.
How Do You Combine Strings in Python?
Concatenation means joining strings together. In Python, you use the + operator. It's like snapping two LEGO pieces together to make something longer.
Repetition uses the * operator. It repeats a string a given number of times. This is surprisingly useful for creating separators, patterns, or padding.
How Do You Find the Length of a String?
The len() function tells you how many characters are in a string. This includes letters, numbers, spaces, and special characters. Every character counts.
How Do You Check If Text Exists Inside a String?
The in operator checks whether one string appears inside another. It returns True or False. Think of it like using Ctrl+F to search for a word in a document.
What Are Escape Characters in Python Strings?
Some characters are impossible to type directly inside a string. How do you put a line break in a string? Or a tab? You use escape characters -- special sequences that start with a backslash \.
| Here's a quick reference of the escape characters you'll use most often: | ||
|---|---|---|
| --- | --- | --- |
\n | New line | Text on a new line |
\t | Tab | Adds tab spacing |
\\ | Backslash | Prints a single \ |
\" | Double quote | Prints " inside a " string |
\' | Single quote | Prints ' inside a ' string |
Why Can't You Change a Character in a Python String?
Strings in Python are immutable. That means once a string is created, you cannot change any of its characters. You can't swap out a letter or fix a typo inside an existing string.
Think of a string like a printed book. You can read any page, but you can't erase a word and write a new one. If you want to change something, you have to print a new book.
So how do you "change" a string? You create a new string with the changes you want. Slicing and concatenation make this easy.
word = "Hello"
word[0] = "J" # TypeError!word = "Hello"
new_word = "J" + word[1:]
print(new_word) # JelloPractice Exercises
Time to practice! These exercises cover everything from this tutorial. They start easy and build up.
Try each one before looking at hints. Making mistakes and reading error messages is how you actually learn.
You are given two variables: first_name set to "Ada" and last_name set to "Lovelace". Create a variable called greeting that combines them into a message, then print it.
Expected output:
Hello, Ada Lovelace! Welcome to Python.Use string concatenation (+) to build the greeting.
You are given a variable word set to "Programming". Print the first character and the last character on separate lines.
Expected output:
P
gUse string indexing to access each character.
You are given a variable text set to "Python". Print the string reversed.
Expected output:
nohtyPUse string slicing to reverse it in one step.
Without running the code, predict what each line will print. Remember: slicing uses [start:stop] where stop is excluded.
Write your predictions as comments, then run the code to check.
This code tries to fix a typo by changing a character directly. But strings are immutable, so it crashes.
Fix the code so it prints:
Hello WorldCreate a new string instead of modifying the old one.
You are given a sentence and a search_word. Check if the search word exists in the sentence (case-insensitive) and print the result.
Expected output:
TrueConvert both to the same case before checking.
You are given an email address stored in email. Extract just the domain name (the part after the @ symbol) and print it.
Expected output:
gmail.comUse the .find() method to locate the @ symbol, then use slicing to extract everything after it.
Summary: Python Strings
| Here's a quick reference of everything you learned: | ||
|---|---|---|
| --- | --- | --- |
| Create a string | "text" or 'text' | name = "Alice" |
| Indexing | string[i] | "Hello"[0] gives "H" |
| Negative indexing | string[-i] | "Hello"[-1] gives "o" |
| Slicing | string[start:stop] | "Hello"[1:4] gives "ell" |
| Step slicing | string[::step] | "Hello"[::-1] gives "olleH" |
| Concatenation | + | "Hi" + " there" gives "Hi there" |
| Repetition | * | "Ha" * 3 gives "HaHaHa" |
| Length | len(string) | len("Hello") gives 5 |
| Membership | in | "fox" in "a fox" gives True |
| Escape characters | \n, \t, \\ | Special characters in strings |
Key takeaway: Strings are immutable. You can read characters, slice them, search them, and combine them -- but you can never change a string in place. Any "change" creates a brand new string.
What's Next?
Now that you can create and slice strings, it's time to learn how to transform them. In the next tutorial -- [Python String Methods](/python/python-string-methods) -- you'll discover built-in methods like .upper(), .replace(), .split(), and .strip() that make working with text a breeze.