Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print[]
function:
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print[a]
Try it Yourself »
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur
adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print[a]
Try it Yourself »
Note: in the result, the line breaks are inserted at the same position as in the code.
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 [remember that the first character has the position 0]:
a = "Hello, World!"
print[a[1]]
Try it Yourself »
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for
loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print[x]
Try it Yourself »
Learn more about For Loops in our Python For Loops chapter.
String Length
To get the length of a string, use the len[]
function.
Example
The len[]
function returns the length of a string:
a = "Hello, World!"
print[len[a]]
Try it Yourself »
Check String
To check if a certain phrase or character is present in a string, we can use the keyword
in
.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print["free" in txt]
Try it Yourself »
Use it in an if
statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print["Yes,
'free' is present."]
Try it Yourself »
Learn more about If statements in our Python If...Else chapter.
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in
.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print["expensive" not in txt]
Try it Yourself »
Use it in an if
statement:
Example
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print["No, 'expensive' is NOT present."]
Try it Yourself »
Summary: in this tutorial, you’ll learn about Python string and its basic operations.
Introduction to Python string
A string is a series of characters. In Python, anything inside quotes is a string. And you can use either single or double quotes. For example:
Code language: Python [python]
message = 'This is a string in Python' message = "This is also a string"
If a string contains a single quote, you should place it in double-quotes like this:
Code language: Python [python]
message = "It's a string"
And when a string contains double quotes, you can use the single quotes:
Code language: Python [python]
message = '"Beautiful is better than ugly.". Said Tim Peters'
To escape the quotes, you use the backslash [\
]. For example:
Code language: Python [python]
message = 'It\'s also a valid string'
The Python interpreter will treat the backslash character [\] special. If you don’t want it to do so, you can use raw strings by adding the letter r
before the first quote. For example:
Code language: Python [python]
message = r'C:\python\bin'
Creating multiline strings
To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’. For example:
Code language: Python [python]
help_message = ''' Usage: mysql command -h hostname -d database name -u username -p password ''' print[help_message]
It’ll output the following if you execute the program:
Code language: Python [python]
Usage: mysql command -h hostname -d database name -u username -p password
Using variables in Python strings with the f-strings
Sometimes, you want to use the values of variables in a string.
For example, you may want to use the value of the name
variable inside the message
string variable:
Code language: Python [python]
name = 'John' message = 'Hi'
To do it, you place the letter f
before the opening quotation mark and put the brace around the variable name:
Code language: Python [python]
name = 'John' message = f'Hi {name}' print[message]
Python
will replace the {name}
by the value of the name
variable. The code will show the following on the screen:
Code language: Python [python]
Hi John
The message
is a format string, or f-string in short. Python introduced the f-string in version 3.6.
Concatenating Python strings
When you place the string literals next to each other, Python automatically concatenates them into one string. For example:
Code language: Python [python]
greeting = 'Good ' 'Morning!' print[greeting]
Output:
Code language: Python [python]
Good Morning!
To concatenate two string variables, you use the operator +
:
Code language: Python [python]
greeting = 'Good ' time = 'Afternoon' greeting = greeting + time + '!' print[greeting]
Output:
Code language: Python [python]
Good Afternoon!
Accessing string elements
Since a string is a sequence of characters, you can access its elements using an index. The first character in the string has an index of zero.
The following example shows how to access elements using an index:
Code language: Python [python]
str = "Python String" print[str[0]] # P print[str[1]] # y
How it works:
- First, create a variable that holds a string
"Python String"
. - Then, access the first and second characters of the string by using the square brackets
[]
and indexes.
If you use a negative index, Python returns the character starting from the end of the string. For example:
Code language: Python [python]
str = "Python String" print[str[-1]] # g print[str[-2]] # n
The following illustrates the indexes of the string
"Python String"
:
Code language: Python [python]
+---+---+---+---+---+---+---+---+---+---+---+---+---+ | P | y | t | h | o | n | | S | t | r | i | n | g | +---+---+---+---+---+---+---+---+---+---+---+---+---+ 0 1 2 3 4 5 6 7 8 9 10 11 12 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Getting the length of a string
To get the length of a string, you use the len[]
function. For example:
Code language: Python [python]
str = "Python String" str_len = len[str] print[str_len]
Output:
Code language: Python [python]
13
Slicing strings
Slicing allows you to get a substring from a string. For example:
Code language: Python [python]
str = "Python String" print[str[0:2]]
Output:
Code language: Python [python]
Py
The str[0:2]
returns a substring that includes the character from the index 0 [included] to
2 [excluded].
The syntax for slicing is as follows:
Code language: Python [python]
string[start:end]
The substring always includes the character at the start
and excludes the string at the end
.
The start
and end
are optional. If you omit the start
, it defaults to zero. If you omit the end
, it defaults to the string’s length.
Python strings are immutable
Python strings are immutable. It means that you cannot change the string. For example, you’ll get an error if you update one or more characters in a string:
Code language: Python [python]
str = "Python String" str[0] = 'J'
Error:
Code language: Python [python]
Traceback [most recent call last]: File "app.py", line 2, in str[0] = 'J' TypeError: 'str' object does not support item assignment
When want to modify a string, you need to create a new one from the existing string. For example:
Code language: Python [python]
str = "Python String" new_str = 'J' + str[1:] print[new_str]
Output:
Code language: Python [python]
Jython String
Summary
- In Python, a string is a series of characters. Also, Python strings are immutable.
- Use quotes, either single quotes or double quotes to create string literals.
- Use the backslash character
\
to escape quotes in strings - Use raw strings
r'...'
to escape the backslash character. - Use f-strings to insert substitute variables in literal strings.
- Place literal strings next to each other to concatenate them. And use the + operator to concatenate string variables.
- Use the
len[]
function to get the size of a string. - Use the
str[n]
to access the character at the position n of the stringstr
. - Use slicing to extract a substring from a string.
Did you find this tutorial helpful ?