In this tutorial you'll learn how to create and work with strings in Python. Examples and practice exercises are included.
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.
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.
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"
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.
Anytime your program needs to deal with text, you'll need strings.
A program might need strings to represent:
It's almost impossible to write realistically-sized programs without using strings.
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.
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'
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!")
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.
You can use +
to concatenate (combine) strings:
>>> print("a" + "b")
ab
You can even multiply a string with a number:
>>> "a"*3
'aaa'
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
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.
Use the len()
function on a string to find its length:
>>> len("Hello")
5
>>> name = "Bob"
>>> print(len(name))
3
Strings are objects. They have various useful methods. Here are some of them.
Use the .lower()
method:
>>> "Hi There".lower()
'hi there'
Use the .upper()
method:
>>> "Hi There".upper()
'HI THERE'
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'
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.."
Use the .find()
method to find the index:
>>> "Hello".find("lo")
3
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']
Use the .startswith()
method:
>>> "Hello".startswith("He")
True
There is also an .endswith()
method.
Our practice lesson lets you practice using strings by writing code and having it automatically run and checked. Try it now!
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!