Skip to main content
Editor

Python Strings: Create, Access, Slice, and Manipulate Text

Beginner25 min8 exercises165 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/8 exercises

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.

Three ways to create strings
# Single quotes
greeting = 'Hello, world!'
print(greeting) # Hello, world!
# Double quotes - exactly the same
greeting = "Hello, world!"
print(greeting) # Hello, world!
# Triple quotes - for multi-line text
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you."""
print(poem)
Output
Hello, world!
Hello, world!
Roses are red,
Violets are blue,
Python is awesome,
And so are you.

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.

Mixing quote types
# Use double quotes when your text has single quotes
message = "It's a beautiful day"
print(message)
# Use single quotes when your text has double quotes
html = '<div class="container">Hello</div>'
print(html)
Output
It's a beautiful day
<div class="container">Hello</div>

Even an empty pair of quotes creates a string. An empty string has zero characters but is still a valid string.

Empty strings vs strings with spaces
empty = ""
print(type(empty)) # <class 'str'>
print(len(empty)) # 0
# A string with just a space is NOT empty
space = " "
print(len(space)) # 1
Output
<class 'str'>
0
1

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.

Accessing characters with positive indices
word = "Python"
# Positive indexing (left to right)
# P y t h o n
# 0 1 2 3 4 5
print(word[0]) # P - first character
print(word[1]) # y - second character
print(word[5]) # n - last character
Output
P
y
n

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.

Accessing characters with negative indices
word = "Python"
# Negative indexing (right to left)
# P y t h o n
# -6 -5 -4 -3 -2 -1
print(word[-1]) # n - last character
print(word[-2]) # o - second to last
print(word[-6]) # P - first character
Output
n
o
P

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.

Basic string slicing
text = "Hello, World!"
# text[start:stop] - includes start, excludes stop
print(text[0:5]) # Hello - characters 0,1,2,3,4
print(text[7:12]) # World - characters 7,8,9,10,11
print(text[0:1]) # H - just one character
Output
Hello
World
H

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.

Slicing shortcuts
text = "Hello, World!"
print(text[:5]) # Hello - from the beginning up to (not including) index 5
print(text[7:]) # World! - from index 7 to the end
print(text[:]) # Hello, World! - the whole string
Output
Hello
World!
Hello, World!

How Does the Step Parameter Work in Slicing?

There's a third number you can add: string[start:stop:step]. The step sets how far to jump from one character to the next. A step of 2 grabs every other character.

Slicing with a step
text = "abcdefghij"
# Every other character
print(text[::2]) # acegi - step of 2
# Every third character
print(text[::3]) # adgj - step of 3
# Slice and step together
print(text[1:8:2]) # bdfh - start at 1, stop before 8, step 2
Output
acegi
adgj
bdfh

The most famous use of the step parameter is reversing a string. A step of -1 walks backwards through the entire string.

Reversing a string with [::-1]
word = "Python"
# Reverse a string with [::-1]
print(word[::-1]) # nohtyP
# This works on any string
print("racecar"[::-1]) # racecar - a palindrome!
Output
nohtyP
racecar

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.

Joining strings with +
first_name = "Ada"
last_name = "Lovelace"
# Concatenation with +
full_name = first_name + " " + last_name
print(full_name) # Ada Lovelace
# You can chain as many as you want
greeting = "Hello" + ", " + "world" + "!"
print(greeting) # Hello, world!
Output
Ada Lovelace
Hello, world!

Repetition uses the * operator. It repeats a string a given number of times. This is surprisingly useful for creating separators, patterns, or padding.

Repeating strings with *
# Repeat a string with *
print("Ha" * 3) # HaHaHa
print("-" * 30) # ------------------------------
print("abc " * 4) # abc abc abc abc
# Great for creating visual separators
title = "My Report"
print(title)
print("=" * len(title)) # =========
Output
HaHaHa
------------------------------
abc abc abc abc 
My Report
=========

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.

Measuring string length
message = "Hello, World!"
print(len(message)) # 13
# Spaces count!
print(len("a b c")) # 5 - three letters + two spaces
# Empty string has length 0
print(len("")) # 0
# Common use: get the last index
word = "Python"
last_index = len(word) - 1
print(word[last_index]) # n
Output
13
5
0
n

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.

Searching with the in operator
sentence = "The quick brown fox jumps over the lazy dog"
# Check if a word is in the sentence
print("fox" in sentence) # True
print("cat" in sentence) # False
print("quick" in sentence) # True
# Check if something is NOT in the string
print("cat" not in sentence) # True
Output
True
False
True
True
Handling case sensitivity with in
# Case-sensitive gotcha
text = "Hello World"
print("hello" in text) # False - wrong case!
print("hello" in text.lower()) # True - convert to lowercase first
# Practical example: checking user input
user_answer = "Yes"
if "yes" in user_answer.lower():
print("User said yes!")
Output
False
True
User said yes!

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 \.

Common escape characters
# \n - new line
print("Line 1\nLine 2\nLine 3")
# \t - tab
print("Name\tAge\tCity")
print("Alice\t25\tParis")
print("Bob\t30\tTokyo")
# \\ - literal backslash
print("File path: C:\\Users\\Documents")
# \" or \' - quote inside a string
print("She said \"hello\"")
Output
Line 1
Line 2
Line 3
Name	Age	City
Alice	25	Paris
Bob	30	Tokyo
File path: C:\Users\Documents
She said "hello"

Here's a quick reference of the escape characters you'll use most often:

EscapeWhat it doesExample output
\nNew lineText on a new line
\tTabAdds tab spacing
\\BackslashPrints a single \
\"Double quotePrints " inside a " string
\'Single quotePrints ' 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.

Strings cannot be changed in place
word = "Hello"
# This will CRASH with a TypeError
try:
word[0] = "J" # Can't change individual characters!
except TypeError as e:
print(f"Error: {e}")
Output
Error: 'str' object does not support item assignment

So how do you "change" a string? You create a new string with the changes you want. Slicing and concatenation make this easy.

Fails: modifying a string in place
word = "Hello"
word[0] = "J"  # TypeError!
Works: creating a new string
word = "Hello"
new_word = "J" + word[1:]
print(new_word)  # Jello

Practice 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.

Exercise 1: Build a Greeting with Concatenation
Write Code

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.

first_name = "Ada"
last_name = "Lovelace"
# Create the greeting using concatenation (+)
# Print the greeting
Exercise 2: Get the First and Last Character
Write Code

You are given a variable word set to "Programming". Print the first character and the last character on separate lines.

Expected output:

P
g

Use string indexing to access each character.

word = "Programming"
# Print the first character
# Print the last character
Exercise 3: Reverse a String
Write Code

You are given a variable text set to "Python". Print the string reversed.

Expected output:

nohtyP

Use string slicing to reverse it in one step.

text = "Python"
# Print the reversed string using slicing
Exercise 4: Predict the Slice Output
Predict Output

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.

word = "Hello"
print(word[1:4]) # Your prediction:
print(word[:3]) # Your prediction:
print(word[2:]) # Your prediction:
Exercise 5: Fix the Bug: Mutating a String
Fix the Bug

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 World

Create a new string instead of modifying the old one.

message = "Hello Wurld"
# Fix the typo: change "u" to "o"
message[7] = "o"
print(message)
Exercise 6: Check If a Word Is in a Sentence
Write Code

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:

True

Convert both to the same case before checking.

sentence = "The quick brown Fox jumps over the lazy Dog"
search_word = "fox"
# Check if search_word is in sentence (case-insensitive)
# Print True or False
Exercise 7: Extract a Domain from an Email Address
Write Code

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.com

Use the .find() method to locate the @ symbol, then use slicing to extract everything after it.

email = "alice@gmail.com"
# Find the position of the @ symbol
# Slice the string to get the domain
# Print the domain
Rotate the Letters
Stretch

Write a function rotate(text, n) that moves the first n characters of text to the end. A negative n rotates the other way: the last characters move to the front.

rotate("python", 2)    # 'thonpy'
rotate("python", -1)   # 'npytho'
rotate("python", 6)    # 'python' (a full turn)

n can be bigger than the length of the text, in either direction: rotating "python" by 8 is a full turn plus 2 more. text always has at least one character.

The def line is written for you: put your code under it, indented four spaces, and end with return and your answer. Check calls rotate() with its own words, some of them hidden. (Functions get their own lesson later.)

def rotate(text, n):
pass
Solution unlocks after your first Check

Summary: Python Strings

Here's a quick reference of everything you learned:

ConceptSyntaxExample
Create a string"text" or 'text'name = "Alice"
Indexingstring[i]"Hello"[0] gives "H"
Negative indexingstring[-i]"Hello"[-1] gives "o"
Slicingstring[start:stop]"Hello"[1:4] gives "ell"
Step slicingstring[::step]"Hello"[::-1] gives "olleH"
Concatenation+"Hi" + " there" gives "Hi there"
Repetition*"Ha" * 3 gives "HaHaHa"
Lengthlen(string)len("Hello") gives 5
Membershipin"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 - you'll discover built-in methods like .upper(), .replace(), .split(), and .strip() that make working with text a breeze.

Harder problems

More problems on this topic: Strings

Related Tutorials

Was this tutorial helpful?