Please enable JavaScript to use CodeHS

Python Tutorial

Python Strings

A string is text your program can hold onto: letters strung together like beads on a bracelet. Learn to create strings, join them, and use Python's built-in tools to transform them.

python ~20 min Beginner friendly
The Big Idea

What is a string?

In computer science, a string is a finite sequence of characters - letters, digits, spaces, punctuation, even emoji - strung together in order, like beads on a friendship bracelet. Strings are how programs handle text: names, messages, passwords, song lyrics, all of it.

Python comes with a whole toolbox of operators, functions, and methods that make working with strings easy. By the end of this tutorial you'll know how to create strings, glue them together, measure them, transform them, and search inside them.

Key word: a sequence means the order matters and every character has a numbered position. "dog" and "god" use the same letters but are different strings!

Syntax

Creating strings

To create a string, you bookend your characters with quotes - either single quotes or double quotes, your choice. You can also use three sets of either kind of quote. Triple quotes aren't required, but they're usually saved for strings that take up multiple lines.

All four examples below create a string, then store it in a variable so we can print it. Press Run to see the output:

main.py
# All examples are the equivalent of one another.

example_1 = '1. Single quotes!'
print(example_1)

example_2 = "2. Double quotes!"
print(example_2)

example_3 = '''3. 3 Sets of single quotes!'''
print(example_3)

example_4 = """4. This sentence is bookended by 3
sets of quotes as well! It doesn't matter
if you use single or double quotes.
The outcome is the same!"""
print(example_4)
Console
1. Single quotes!
2. Double quotes!
3. 3 Sets of single quotes!
4. This sentence is bookended by 3
sets of quotes as well! It doesn't matter
if you use single or double quotes.
The outcome is the same!

Pro tip: pick one style and stick with it. One time the choice really matters: if your text contains an apostrophe, like "It doesn't matter", wrap it in double quotes so Python doesn't think the string ends early.

Look Closer

Triple quotes vs comments

Take a close look at example 4 above. Its formatting looks a lot like Python's multi-line comment trick, where programmers use three quotes to write notes the program ignores. So why did it print?

The difference is where the quotes sit. When triple quotes are placed inline - starting and ending inside a real piece of code, like being assigned to a variable and passed to print() - the text is a string the program actually reads. When triple quotes just sit on their own, Python treats the whole block as a comment and skips it.

The program below has two nearly identical blocks. Each has a variable, some text, and a print(). Only one prints. Run it and see:

main.py
# This example illustrates the difference
# between comments and strings in Python.


# Bookending triple quotes
'''python_comment = This is an example of
how to create multi-line comment.
print(python_comment)
'''
# In-line triple quotes
python_string = '''Why does this function print onto
the screen, while the previous
function does not?'''
print(python_string)
Console
Why does this function print onto
the screen, while the previous
function does not?

The first block is wrapped entirely inside the triple quotes, so everything in it - even the print() - is just a comment. In the second block, the triple quotes only wrap the text, so python_string is a real string and the print runs.


Interactive

The string workbench

Time to get hands-on. Type anything into the workbench below and watch Python's view of your string update live: every character gets its own tile (with its position number underneath), and the most useful string tools run on it instantly.

String Workbench

Your string

s = ""
len(s)
s.upper()
s.lower()
s.title()

Concatenation builder

"" + "" + ""

Result

The classic gotcha

"5" + "3"

→ "53"

These are strings, so + glues the characters together. It doesn't do math!

5 + 3

→ 8

No quotes means these are numbers, so + adds them.

Need to switch teams? int("5") turns the string "5" into the number 5, and str(5) turns the number 5 back into a string. Mixing a string and a number with + gives an error, so convert first.


String Operations

Joining strings together

Gluing two or more strings into one is called concatenation, and Python gives you a couple of ways to do it.

Side by side (string literals only)

If you write string literals right next to each other, Python quietly joins them into one string:

main.py
snack = "PB " "& " "J "
print(snack)
Console
PB & J 

The + operator (works with variables)

The side-by-side trick only works with string literals - text typed directly in quotes. Once a string is stored in a variable, use the + operator to join it with other strings:

main.py
schmear_1 = "PB "
schmear_2 = "J "

print(str(schmear_1) + "& " + str(schmear_2))
Console
PB & J 

About str(): the str() function returns a value as a string. Here the variables already hold strings, so str() just plays it safe. Where it becomes essential is with numbers: "I am " + str(12) works, but "I am " + 12 crashes, because + can't join a string with a number directly.

The Toolbox

len() and string methods

You already met these in the workbench - here's what they look like in code. The len() function tells you how many characters a string has (spaces count!). String methods are transformations you call with a dot after the string, like .upper():

main.py
phrase = "Code rocks"

print(len(phrase))       # how many characters?
print(phrase.upper())    # SHOUT IT
print(phrase.lower())    # whisper it
print(phrase.title())    # Capitalize Each Word
Console
10
CODE ROCKS
code rocks
Code Rocks

Good to know: methods don't change the original string - they hand you a brand new one. After all four prints, phrase is still "Code rocks".


String Operations

Searching with in

Python can also sift through a string to check whether a character or a substring (a smaller piece of a string) is inside it. The membership operator in answers with a boolean: True if it's found, False if not. That makes it perfect for if statements:

main.py
poppins = "supercalifragilisticexpialidocious"
if 'cali' in poppins:
    print('Congrats, you get a spoon full of sugar!')
Console
Congrats, you get a spoon full of sugar!

Capitalization is key: if we searched for 'Cali' instead, the program would consider it missing and the print would never run. To Python, 'c' and 'C' are different characters.

Also note that in only reports whether something is present. The letter "i" appears seven times in poppins, but 'i' in poppins just says True - it doesn't count.

Want the opposite check? In true Python fashion, just change in to not in. This version prints nothing at all, because 'cali' is present:

main.py
poppins = "supercalifragilisticexpialidocious"
if 'cali' not in poppins:
    print('Congrats, you get a spoon full of sugar!')
Console
(nothing prints - 'cali' IS in the string)
A Sneak Peek

A taste of indexing

Remember the position numbers under each tile in the workbench? Those are indexes, and you can use them with square brackets to grab any single character. Counting starts at 0, not 1:

main.py
word = "string"
print(word[0])   # the FIRST character
print(word[5])   # the last one (6 letters, so index 5)
Console
s
g

There's a lot more you can do with indexes - including grabbing whole chunks at once. That's a tutorial of its own: check out Indexing Python Strings when you're ready.


Your Turn

Practice challenges

To recap: strings are a finite sequence of characters. You've seen how they're created, how to join them, how to measure and transform them, and how to check what's inside them. Try these challenge scenarios, then reveal each answer to check yourself.

1

Name that operator

What type of operators are in and not in? Hint: it's a type of "belonging."

They are membership operators. They check whether a character or substring belongs to (is a member of) a string, and answer with True or False.

2

Name that function

What is the name of the function you would use to return an object as a string?

The str() function. For example, str(12) returns the string "12", which you can then concatenate with other strings.

3

Marquis's chat bot

Marquis is programming an automated chat box for their school project using Python. When a user enters their name, the bot replies "Hi, {name}! Someone will be with you shortly." If name is the only object inside the print() function, which method did Marquis use to concatenate everything together?

Marquis used the + operator with str(), joining the variable to the string literals around it - since name is stored in a variable, the side-by-side literal trick won't work.

solution.py
name = "Marquis"
print("Hi, " + str(name) + "! Someone will be with you shortly.")
Console
Hi, Marquis! Someone will be with you shortly.

Code

A string example

Strings have built-in tools for changing text. This program shows some common string methods in Python.


Check Yourself

Quick quiz

1. Which of these is NOT a valid way to create a string in Python?

2. What does print("5" + "3") output?

3. What does this program print?

word = "Karel"
if "k" in word:
    print("Found it!")
print(len(word))

Keep learning Python

You can create strings, join them, transform them, and search them. Next, learn to grab any character with indexing, then pull out whole chunks with slicing.