Python Strings Explained: Learn the Fundamentals of this Core Data Type

Written by Brendon
10 February 2025

Strings in Python are a fundamental data type. Learn how to define and work with them effectively in this ultimate beginner guide.

Spaceship deck

Join Our Neural Network

Subscribe to receive mission updates and backend development insights.

Single vs Double Quotes #

Python is very lenient when it comes to the style of quotes you choose. For example both of the following are perfectly valid:

print("Wecome to Python")

print('Python is awesome')

Notice how we've used double quotes in the first line and single quotes in the second. No problem, both are valid.

The main rule to remember is that you can't wrap a string in differing single and double quotes. For example the following is not valid:

print("This is not valid')

So you're probably asking, which should I use? Well it often comes down to personal and team preference.

Decide on which one you prefer and stick with it. Aim to be consistent. If you're working on a team who have decided on one versus the other, go with that.

Apostrophe's in Strings #

What if you prefer wrapping strings in single quotes but you need to include an apostrophe in the string?

print('It's time to power up')

The above example won't work because technically we've ended the string after "It". Fortunately there's an easy way around this called escaping.

From Wikipedia:

In computing and telecommunications, an escape character is a character that invokes an alternative interpretation on the following characters in a character sequence.

print('It\'s time to power up')
It's time to power up

Now that will work. Notice how we added a backslash before the apostrophe? That's the escape character which lets the python interpreter know to encode the following character(s) differently.

Triple Quotes #

Ok so we've covered single and double quotes, now let's move on to triple quotes. In Python, you'll generally either use these in multi-line strings or docstrings.

Multi-line Strings #

Sometimes we've got a really long string like this:

message = "Our in game space ship needs to power up before it can leave the launch bay. Validate that at least one playable character is on board."

The message is long, hard to read and generally doesn't fit horizontally on a screen. So lets use triple quotes instead to create a multi-line string:

message = """Our in game space ship needs to power up
before it can leave the launch bay. Validate that at
least one playable character is on board."""

Now our long string is must easier to read.

Docstrings #

Docstrings are another common place where triple quotes come in handy.

From Wikipedia

In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code.

In Python, you'll generally use docstrings to explain what modules, classes or functions do. For example:

def perform_attack(enemy_health, damage):
    """Perform an enemy attack by reducing an enemy's health by the
    specified damage.

    Paramaters
    ----------
    enemy_health: int
        An enemy's current health
    damage: int
        The amount of damage to apply to the enemy's health

    Returns
    -------
    int
        The new enemy health value after damage has been applied
    """" 
    return max(enemy_health - damage, 0)

As you can see, docstrings can become quite elaborate and detailed. But they don't have to be provided they clearly explain the piece of code they're intended to explain.

Joining Strings #

Sometimes we'll run in to situations where we need to join strings together. The two options I'll cover for doing this are concatenation and the tuple trick.

String Concatenation #

So we've got two variables containing strings which we need to turn into a single string. How do we go about doing this? Our first option is to simply add them together, better known as concatenation.

player_name = "Captain Blake"
message = "has taken 10HP damage."

print(player_name + " " + message)
Captain Blake has taken 10HP damage

Pretty straight forward. We simply add (concatenate) each string together and in our case, we include a space in the middle.

Implicit String Concatenation (Tuple Trick) #

I like to refer to this one as the tuple trick and I find myself using it quite a lot. Here's how it works:

message = (
    "Captain Blake"
    " has taken 10HP damage."
)
print(message)

new_message = "Captain Blake" " has taken 25HP damage."
print(message)
Captain Blake has taken 10HP damage
Captain Blake has taken 25HP damage

As you can see, Python allows us to define multiple string literals within parentheses or directly next to each other. The result will be interpreted as a single string.

The tuple trick might not initially look very useful, but when you combine it with F Strings which I'll cover later in this article, they become really handy.

Formatted Strings #

So we're designing a game where we've got a player character and a damage value. We want to print out a string letting the player know that their character just took a certain amount of damage.

Here's our string along with our variables:

player_name = "Captain Blake"
damage = 10
message = "has taken HP damage"

How do we do that? How do we get those variables into the string and print out our message?

Format Method #

Our first option is to use the .format() method provided on all strings.

This is the older way of getting the job done so I'm covering this first quickly before moving on to the new hotness.

By placing {} parenthesis within your string in the places you want to inject your variables, you're able to append .format() to your string and specify which variables should be injected in the correct order.

message = "{} has taken {}HP damage".format(player_name, damage)
print(message)
'Captain Blake has taken 10HP damage'

F Strings #

Next up we've got F Strings which are a newer addition to Python and are almost always preferred due to their reduced verbosity and ease of reading.

To use them we include {} parenthesis within the string (just like the format method) but this time we include the variables directly inside the parenthesis. We also prepend the string with the letter f.

message = f"{player_name} has taken {damage}HP damage"
print(message)
'Captain Blake has taken 10HP damage'

Pretty cool right? Now you can read the sentence from left to right without your eyes needing to jump to the end constantly to check which variable is injected into which place.

Slicing Strings #

Ok so we've got handle on the basics of creating strings. What do we do when we've got a string but we only care about a small part of it, maybe the first 3 characters.

Slicing strings in Python gives us the ability to refer to a subset of characters within a string. But before we get head of ourselves, we need to understand how indexing works in Python.

String Indexing #

An index refers to an items position within a sequence. Since we're dealing with strings, an index refers to the position of a character within the overall string.

In Python you have both positive and negative indexing:

  P   y   t   h   o   n
  0   1   2   3   4   5   →  Positive Indexing
 -6  -5  -4  -3  -2  -1   →  Negative Indexing

NB: The important thing to note is that indexes start at zero. This means that the first character of a string (or any sequence) is not at index 1, but is actually at index 0.

space_ship_class = "Destroyer"
print(space_ship_class[3])
print(space_ship_class[-3])
print(space_ship_class[6])
t
y
y

Now that we can refer to specific characters within a string based on their index, we can start working with slices.

Basics of Slicing #

While there's more to slicing than what I'll explain here, this will be enough to get you going with the most common usage patterns.

Ok let's jump in. Getting a range of characters from within a string by leveraging slicing works by specifying a start and end index.

An important thing to keep in mind is that the start index is inclusive and the end index is exclusive. Don't worry, this will make more sense with an example.

If we're only interested in the first 4 characters of a string, here's how we'll leverage slicing:

space_ship_class = "Destroyer"
print(space_ship_class[0:4])
Dest

This gives us the first 4 characters of the string starting at index 0 and moving to index 3 (Remember, the second index is exclusive).

Pro tip: If the start position is 0, we can just leave it out like this:

space_ship_class = "Destroyer"
print(space_ship_class[:4])
Dest

Now for an example using negative indexing:

space_ship_class = "Destroyer"
print(space_ship_class[-4:-2])
print(space_ship_class[-4:])
oy
oyer

The key here is to start counting from the end of the string and move your way to the beginning.

Pro tip: If you want to slice all the way to the end of the string, you can leave out the second value.

String Methods #

Almost time to wrap this article up. But first, I'll rapid fire a few handy string methods which you'll likely need fairly often.

A quick note, when I say string methods, I'm referring to methods which are available when you follow a string with a period which then gives you access to several useful pieces of functionality that you can perform on the string.

Lower and Upper #

Calling lower on a string will convert all characters within the string to lower case. Likewise calling upper will convert all characters to upper case.

message = "Captain Blake has taken 10HP damage"
print(message.upper())
print(message.lower())
CAPTAIN BLAKE HAS TAKEN 10HP DAMAGE
captain blake has taken 10hp damage

Count #

Need to know how many times a certain substring occurs within a string? Count is here to help.

message = "Captain Blake has taken 10HP damage"
print(message.count("ak"))
2

Find #

Find is your go to when you want to know the index position of the first occurrence of a character (or substring).

message = "Captain Blake has taken 10HP damage"
print(message.find("ak"))
10

Replace #

Last up we've got replace which is handy for replacing a character (or substring) with something else.

message = "Captain Blake has taken 10HP damage"
print(message.replace("ZZ"))
Captain BlZZe has tZZen 10HP damage

Getting Help #

While this article doesn't delve into every nook and cranny of strings in Python, it certainly does cover the things you'll use most often.

If you find yourself wanting to know which other string methods are available you've got two options straight from your python REPL.

The first is by passing str to help:

help(str)

What you'll discover here is all the available string methods along with detail on how to use each. This is useful if you're not sure exactly what you're looking for or what's available.

If you know what you're looking for, you can get help on a specific string method:

help(str.count)

With that, you'll get usage instructions for the count method.

You can also get help like this for pretty much everything else Python has to offer. So keep help in mind when you want a quick method for learning how to use something.