Python Principles

Python Strings - An Overview

In this tutorial you'll learn how to create and work with strings in Python. Examples and practice exercises are included.

What's a string?

A string is a sequence of letters. In other words, if you have some letters in a row, that's a string.

In Python, strings are surrounded by quotation marks. This is to tell Python that it's dealing with a string, not a variable.

Examples of strings

Here's a string that represents a name:

"Bob"

Here's a string that represents a password:

"mypassword123"

Here are other examples of strings:

"Hello world"
"this is a string"
"X"
""

That last string is known as the empty string.

How do I use strings in Python?

You create a string by writing letters and surrounding them with single or double quotes. To actually use the string, you need to assign it to a variable or pass it as an argument into a function. For example, this code defines a variable called name that holds a string:

name = "Alice"

Learn about strings

You can use our interactive strings lesson to quickly learn the basics of using strings.

The lesson works by letting you write and run code. Our system automatically checks if your answers are correct and gives you feedback.

What do I need strings for?

Anytime your program needs to deal with text, you'll need strings.

A program might need strings to represent:

  • a username
  • an email address
  • instructions for the user
  • debug messages
  • and much, much more

It's almost impossible to write realistically-sized programs without using strings.

Working with strings

Extracting letters

You can take a letter out of a string with indexing. Use square brackets for this. String indexes start at 0, not 1.

For example, say that we have this string:

name = "Bob"

Now, name[0] will be "B", while name[1] will be "o". So if you run this code:

print(name[0])

It will print a B on your screen.

Extracting part of a string

This is called slicing the string. You use square brackets with a colon. Again, indexing starts at 0, not 1.

For example, say that we have this string:

username = "iamthebob"

Then, we can extract the first three letters:

username[0:3]

This will be "iam".

We can also extract some of the letters in the middle:

>>> username = "iamthebob"
>>> username[3:6]
'the'

Checking if a string contains something

You can use the in keyword to check if a string contains another string. Here's an example:

username = "iamthebob"
if "bob" in username:
    print("It is Bob!")

Getting a string as input

You can call the input function to get input from the user:

username = input("What is your username? ")

If you're still using Python 2, you'll have to use raw_input() instead.

Combining strings

You can use + to concatenate (combine) strings:

>>> print("a" + "b")
ab

You can even multiply a string with a number:

>>> "a"*3
'aaa'

Output with variables

Sometimes you want to put the value of a variable inside a string, for example so that you can output it to the user.

In Python 3, you can use so-called f-strings to accomplish this. You put an f before the quotation marks. This allows you to put any variables inside curly brackets inside the string. For example:

>>> name = "Bob"
>>> age = 33
>>> print(f"Hi {name}, you are {age} years old")
Hi Bob, you are 33 years old

You can also use the % sign for string formatting, although this is outdated:

print("Hi %s, you are %d years old" % (name, age))

Here, %s means a string and %d means a digit.

If you want to avoid f-strings, there is also a format method you can use:

>>> print("Hi {}, you are {} years old".format(name, age))
Hi Bob, you are 33 years old

Reversing a string

This requires slicing with a negative step:

>>> print("abcd"[::-1])
dcba
>>> greeting = "Hello, world"
>>> print(greeting[::-1])
dlrow ,olleH

If you don't understand the slicing, don't worry - just put [::-1] at the end of your string and it'll be reversed.

String length

Use the len() function on a string to find its length:

>>> len("Hello")
5
>>> name = "Bob"
>>> print(len(name))
3

Useful string methods

Strings are objects. They have various useful methods. Here are some of them.

Changing a string to lowercase

Use the .lower() method:

>>> "Hi There".lower()
'hi there'

Changing a string to uppercase

Use the .upper() method:

>>> "Hi There".upper()
'HI THERE'

Replacing part of a string

Use the .replace() method to replace parts of a string with another:

>>> "hi.there".replace(".", " ")
'hi there'

All the occurrences are replaced:

>>> "hello world".replace("l", "xx")
'hexxxxo worxxd'

Remove spaces and tabs

Use the .strip() method to remove whitespace near the beginning and ending of the string:

>>> " this string isn't clean..  ".strip()
"this string isn't clean.."

Find a string in another string

Use the .find() method to find the index:

>>> "Hello".find("lo")
3

Split a string

Use the .split() method to split a string into a list:

>>> "this - is - a - string".split(" - ")
['this', 'is', 'a', 'string']

This lets you easily parse comma-separated values:

>>> "parse,this,csv".split(",")
['parse', 'this', 'csv']

Check if a string starts with

Use the .startswith() method:

>>> "Hello".startswith("He")
True

There is also an .endswith() method.

Practice using strings

Our practice lesson lets you practice using strings by writing code and having it automatically run and checked. Try it now!

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!