1. static.realpython.com/python-basics-sample-chapters.pdf, page 96
4.7. Streamline Your Print Statements
known as f-strings.
The easiest way to understand f-strings is to see them in action. Here’s
what the above string looks like when written as an f-string:
>>> f"{name} has {heads} heads and {arms} arms"
'Zaphod has 2 heads and 3 arms'
There are two important things to notice about the above example:
1. The string literal starts with the letter f before the opening quotation mark.
2. Variable names surrounded by curly braces ({}) are replaced by
their corresponding values without using str().
You can also insert Python expressions between the curly braces. The
expressions are replaced with their result in the string:
>>> n = 3
>>> m = 4
>>> f"{n} times {m} is {n*m}"
'3 times 4 is 12'
It’s a good idea to keep any expressions used in an f-string as simple
as possible. Packing a bunch of complicated expressions into a string
literal can result in code that is difficult to read and difficult to maintain.
f-strings are available only in Python version 3.6 and above. In earlier versions of Python, you can use .format() to get the same results.
Returning to the Zaphod example, you can use .format() to format the
string like this:
>>> "{} has {} heads and {} arms".format(name, heads, arms)
'Zaphod has 2 heads and 3 arms'
f-strings are shorter and sometimes more readable than using .format(). You’ll see f-strings used throughout this book.
95
2. static.realpython.com/python-basics-sample-chapters.pdf, page 98
4.8. Find a String in a String
For an in-depth guide to f-strings and comparisons to other string formatting techniques, check out Real Python’s “Python 3’s f-Strings: An
Improved String Formatting Syntax (Guide).”
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
1. Create a float object named weight with the value 0.2, and create
a string object named animal with the value "newt". Then use these
objects to print the following string using only string concatenation:
0.2 kg is the weight of the newt.
2. Display the same string by using .format() and empty {} placeholders.
3. Display the same string using an f-string.
4.8 Find a String in a String
One of the most useful string methods is .find(). As its name implies,
this method allows you to find the location of one string in another
string—commonly referred to as a substring.
To use .find(), tack it to the end of a variable or a string literal with
the string you want to find typed between the parentheses:
>>> phrase = "the surprise is in here somewhere"
>>> phrase.find("surprise")
4
The value that .find() returns is the index of the first occurrence of the
string you pass to it. In this case, "surprise" starts at the fifth character
of the string "the surprise is in here somewhere", which has index 4
because counting starts at zero.
96
This is a sample from “Python Basics: A Practical
Introduction to Python 3”
With the full version of the book you get a complete Python curriculum
to go all the way from beginner to intermediate-level. Every step along
the way is explained and illustrated with short & clear code samples.
Coding exercises within each chapter and our interactive quizzes help
fast-track your progress and ensure you always know what to focus on
next.
Become a fluent Pythonista and gain programming knowledge you
can apply in the real-world, today:
If you enjoyed the sample chapters you can purchase a full
version of the book at realpython.com/pybasics-book
3. static.realpython.com/python-basics-sample-chapters.pdf, page 66
4.1. What Is a String?
Note
Not every string is a string literal. Sometimes strings are input
by a user or read from a file. Since they’re not typed out with
quotation marks in your code, they’re not string literals.
The quotes surrounding a string are called delimiters because they
tell Python where a string begins and where it ends. When one type of
quotes is used as the delimiter, the other type can be used inside the
string:
string3 = "We're #1!"
string4 = 'I said, "Put it over by the llama."'
After Python reads the first delimiter, it considers all the characters
after it part of the string until it reaches a second matching delimiter.
This is why you can use a single quote in a string delimited by double
quotes, and vice versa.
If you try to use double quotes inside a string delimited by double
quotes, you’ll get an error:
>>> text = "She said, "What time is it?""
File "<stdin>", line 1
text = "She said, "What time is it?""
^
SyntaxError: invalid syntax
Python throws a SyntaxError because it thinks the string ends after the
second ", and it doesn’t know how to interpret the rest of the line. If
you need to include a quotation mark that matches the delimiter inside a string, then you can escape the character using a backslash:
>>> text = "She said, \"What time is it?\""
>>> print(text)
She said, "What time is it?"
65
4. static.realpython.com/python-basics-sample-chapters.pdf, page 65
4.1. What Is a String?
Note
For now, you can think of the word class as a synonym for data
type, although it actually refers to something more specific.
You’ll see just what a class is in chapter 10.
type() also works for values that have been assigned to a variable:
>>> phrase = "Hello, World"
>>> type(phrase)
<class 'str'>
Strings have three important properties:
1. Strings contain individual letters or symbols called characters.
2. Strings have a length, defined as the number of characters the
string contains.
3. Characters in a string appear in a sequence, which means that
each character has a numbered position in the string.
Let’s take a closer look at how strings are created.
String Literals
As you’ve already seen, you can create a string by surrounding some
text with quotation marks:
string1 = 'Hello, World'
string2 = "1234"
You can use either single quotes (string1) or double quotes (string2)
to create a string as long as you use the same type at the beginning
and end of the string.
Whenever you create a string by surrounding text with quotation
marks, the string is called a string literal. The name indicates that
the string is literally written out in your code. All the strings you’ve
seen thus far are string literals.
64
5. edu.anarcho-copy.org/Programming%20Languages/Python/Automate%20the%20Boring%20Stuff%20with%20Python.pdf, page 149
Enter the following into the interactive shell:
>>> print("Hello there!\nHow are you?\nI\'m doing fine.")
Hello there!
How are you?
I'm doing fine.
Raw Strings
You can place an r before the beginning quotation mark of a string to make
it a raw string. A raw string completely ignores all escape characters and
prints any backslash that appears in the string. For example, type the following into the interactive shell:
>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.
Because this is a raw string, Python considers the backslash as part of
the string and not as the start of an escape character. Raw strings are helpful if you are typing string values that contain many backslashes, such as the
strings used for regular expressions described in the next chapter.
Multiline Strings with Triple Quotes
While you can use the \n escape character to put a newline into a string, it
is often easier to use multiline strings. A multiline string in Python begins
and ends with either three single quotes or three double quotes. Any quotes,
tabs, or newlines in between the “triple quotes” are considered part of the
string. Python’s indentation rules for blocks do not apply to lines inside a
multiline string.
Open the file editor and write the following:
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
Save this program as catnapping.py and run it. The output will look
like this:
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
Manipulating Strings 125
6. static.realpython.com/python-basics-sample-chapters.pdf, page 95
4.7. Streamline Your Print Statements
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
1. Create a string containing an integer, then convert that string into
an actual integer object using int(). Test that your new object is
a number by multiplying it by another number and displaying the
result.
2. Repeat the previous exercise, but use a floating-point number and
float().
3. Create a string object and an integer object, then display them side
by side with a single print statement using str().
4. Write a program that uses input() twice to get two numbers from
the user, multiplies the numbers together, and displays the result.
If the user enters 2 and 4, then your program should print the
following text:
The product of 2 and 4 is 8.0.
4.7 Streamline Your Print Statements
Suppose you have a string, name = "Zaphod", and two integers, heads
= 2 and arms = 3. You want to display them in the string "Zaphod has
2 heads and 3 arms". This is called string interpolation, which is
just a fancy way of saying that you want to insert some variables into
specific locations in a string.
One way to do this is with string concatenation:
>>> name + " has " + str(heads) + " heads and " + str(arms) + " arms"
'Zaphod has 2 heads and 3 arms'
This code isn’t the prettiest, and keeping track of what goes inside or
outside the quotes can be tough. Fortunately, there’s another way of
interpolating strings: formatted string literals, more commonly
94
7. static.realpython.com/python-basics-sample-chapters.pdf, page 94
4.6. Working With Strings and Numbers
As you’ve already seen, concatenating a number with a string produces a TypeError:
>>> num_pancakes = 10
>>> "I am going to eat " + num_pancakes + " pancakes."
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Since num_pancakes is a number, Python can’t concatenate it with the
string "I'm going to eat". To build the string, you need to convert
num_pancakes to a string using str():
>>> num_pancakes = 10
>>> "I am going to eat " + str(num_pancakes) + " pancakes."
'I am going to eat 10 pancakes.'
You can also call str() on a number literal:
>>> "I am going to eat " + str(10) + " pancakes."
'I am going to eat 10 pancakes.'
str() can even handle arithmetic expressions:
>>> total_pancakes = 10
>>> pancakes_eaten = 5
>>> "Only " + str(total_pancakes - pancakes_eaten) + " pancakes left."
'Only 5 pancakes left.'
In the next section, you’ll learn how to format strings neatly to display
values in a nice, readable manner. Before you move on, though, check
your understanding with the following review exercises.
93
8. edu.anarcho-copy.org/Programming%20Languages/Python/Automate%20the%20Boring%20Stuff%20with%20Python.pdf, page 49
>>> 'I am ' + 29 + ' years old.'
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
'I am ' + 29 + ' years old.'
TypeError: Can't convert 'int' object to str implicitly
Python gives an error because you can use the + operator only to add
two integers together or concatenate two strings. You can’t add an integer
to a string because this is ungrammatical in Python. You can fix this by
using a string version of the integer instead, as explained in the next section.
The str(), int(), and float() Functions
If you want to concatenate an integer such as 29 with a string to pass to
print(), you’ll need to get the value '29', which is the string form of 29. The
str() function can be passed an integer value and will evaluate to a string
value version of it, as follows:
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old.
Because str(29) evaluates to '29', the expression 'I am ' + str(29) +
' years old.' evaluates to 'I am ' + '29' + ' years old.', which in turn
evaluates to 'I am 29 years old.'. This is the value that is passed to the
print() function.
The str(), int(), and float() functions will evaluate to the string, integer, and floating-point forms of the value you pass, respectively. Try converting some values in the interactive shell with these functions, and watch
what happens.
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
>>> float(10)
10.0
Python Basics 25
9. static.realpython.com/python-basics-sample-chapters.pdf, page 73
4.2. Concatenation, Indexing, and Slicing
If you try to access an index beyond the end of a string, then Python
raises an IndexError:
>>> flavor[9]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
flavor[9]
IndexError: string index out of range
The largest index in a string is always one less than the string’s length.
Since "fig pie" has a length of seven, the largest index allowed is 6.
Strings also support negative indices:
>>> flavor[-1]
'e'
The last character in a string has index -1, which for "fig pie" is the
letter e. The second to last character i has index -2, and so on.
The following figure shows the negative index for each character in
the string "fig pie":
|
f
|
-7
i
-6
|
g
-5
|
|
-4
p
-3
|
i
-2
|
e
|
-1
Just like with positive indices, Python raises an IndexError if you try to
access a negative index less than the index of the first character in the
string:
>>> flavor[-10]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
flavor[-10]
IndexError: string index out of range
Negative indices may not seem useful at first, but sometimes they’re
a better choice than a positive index.
72
10. static.realpython.com/python-basics-sample-chapters.pdf, page 77
4.2. Concatenation, Indexing, and Slicing
Note
The empty string is called empty because it doesn’t contain any
characters. You can create it by writing two quotation marks
with nothing between them:
empty_string = ""
A string with anything in it—even a space—is not empty. All the
following strings are non-empty:
non_empty_string1 = " "
non_empty_string2 = "
"
non_empty_string3 = "
"
Even though these strings don’t contain any visible characters,
they are non-empty because they do contain spaces.
You can use negative numbers in slices. The rules for slices with negative numbers are exactly the same as the rules for slices with positive
numbers. It helps to visualize the string as slots with the boundaries
labeled with negative numbers:
|
-7
f
|
-6
i
|
-5
g
|
|
-4
-3
p
|
-2
i
|
e
|
-1
Just like before, the slice [x:y] returns the substring starting at index
x and going up to but not including y. For instance, the slice [-7:-4]
returns the first three letters of the string "fig pie":
>>> flavor[-7:-4]
'fig'
Notice, however, that the rightmost boundary of the string does not
have a negative index. The logical choice for that boundary would
seem to be the number 0, but that doesn’t work.
76
[1] https://static.realpython.com/python-basics-sample-chapters.pdf#page=96
[2] https://static.realpython.com/python-basics-sample-chapters.pdf#page=98
[3] https://static.realpython.com/python-basics-sample-chapters.pdf#page=66
[4] https://static.realpython.com/python-basics-sample-chapters.pdf#page=65
[5] https://edu.anarcho-copy.org/Programming%20Languages/Python/Automate%20the%20Boring%20Stuff%20with%20Python.pdf#page=149
[6] https://static.realpython.com/python-basics-sample-chapters.pdf#page=95
[7] https://static.realpython.com/python-basics-sample-chapters.pdf#page=94
[8] https://edu.anarcho-copy.org/Programming%20Languages/Python/Automate%20the%20Boring%20Stuff%20with%20Python.pdf#page=49
[9] https://static.realpython.com/python-basics-sample-chapters.pdf#page=73
[10] https://static.realpython.com/python-basics-sample-chapters.pdf#page=77