String Interpolation
When writing strings, you may want to include variables in the output. String interpolation includes the variable names as placeholders within the string. There are two standard methods for achieving string interpolation: comma separators and format.
Comma Separators
Variables may be interpolated into strings using commas to separate clauses. It's similar to the +
operator, except it adds spacing for you.
You can have a look at an example here, where we add Ciao
within a print
statement:
italian_greeting = 'Ciao' print('Should we greet people with', italian_greeting, 'in North Beach?')
You should get the following output:
Should we greet people with Ciao in North Beach?
Format
With format
, as with commas, Python types, ints
, floats
, and so on, are converted into strings upon execution. The format
is accessed using brackets and dot notation:
owner = 'Lawrence Ferlinghetti' age = 100 print('The founder of City Lights Bookstore, {}, is now {} years old.'.format(owner, age))
You should get the following output:
The founder of City Lights Bookstore, Lawrence Ferlinghetti, is now 100 years old.
The format
works as follows: First, define your variables. Next, in the given string, use {}
in place of each variable. At the end of the string, add a dot (.
) followed by the format
keyword. Then, in parentheses, list each variable in the desired order of appearance. In the next section, you will look at the built-in string functions available to a Python developer.
The len() Function
There are many built-in functions that are particularly useful for strings. One such function is len()
, which is short for length. The len()
function determines the number of characters in a given string.
Note that the len()
function will also count any blank spaces in a given string.
You'll use the arabic_greeting
variable used in Exercise 8, Displaying Strings:
len(arabic_greeting)
You should get the following output:
16
Note
When entering variables in Jupyter notebooks, you can use tab completion
. After you type in a letter or two, you can press the Tab key. Python then displays all valid continuations that will complete your expression. If done correctly, you should see your variable listed. Then you can highlight the variable and press Enter. Using tab completion will limit errors.
String Methods
All Python types, including strings, have their own methods. These methods generally provide shortcuts for implementing useful tasks. Methods in Python, as in many other languages, are accessed via dot notation.
You can use a new variable, name
, to access a variety of methods. You can see all methods by pressing the Tab button after the variable name and a dot.
Exercise 10: String Methods
In this exercise, you will learn how to implement string methods.
- Set a new variable, called
name
, to any name that you like:name = 'Corey'
Note
Access string methods by pressing the
Tab
button after the variable name and dot (.
), as demonstrated in the following screenshot:You can scroll down the list to obtain all available string methods.
- Now, convert the name into lowercase letters using the
lower()
function:name.lower()
You should get the following output:
'corey'
- Now, capitalize the name using the
capitalize()
function:name.capitalize()
You should get the following output:
'Corey'
- Convert the name into uppercase letters using
upper()
:name.upper()
You should get the following output:
'COREY'
- Finally, count the number of
o
instances in the word 'Corey
':name.count('o')
You should get the following output:
1
In this exercise, you have learned about a variety of string methods, including lower()
, capitalize()
, upper()
, and count()
.
Methods may only be applied to their representative types. For instance, the lower()
method only works on strings, not integers or floats. By contrast, built-in functions such as len()
and print()
can be applied to a variety of types.
Note
Methods do not change the original variable unless we explicitly reassign the variable. So, the name has not been changed, despite the methods that we have applied.
Casting
It's common for numbers to be expressed as strings when dealing with input and output. Note that '5'
and 5
are different types. We can easily convert between numbers and strings using the appropriate type keywords. In the following exercise, we are going to be using types and casting to understand the concepts much better.
Exercise 11: Types and Casting
In this exercise, you will learn how types and casting work together:
- Open a new Jupyter Notebook.
- Determine the type of
'5'
:type('5')
You should get the following output:
str
- Now, add '5' and '7':
'5' + '7'
You should get the following output:
'57'
The answer is not 12 because, here,
5
and7
are of type string, not of typeint
. Recall that the+
operator concatenates strings. If we want to add5
and7
, we must convert them first. - Convert the '5' string to an
int
using the code mentioned in the following code snippet:int('5')
You should get the following output:
5
Now
5
is a number, so it can be combined with other numbers via standard mathematical operations. - Add '5' and '7' by converting them to
int
first:int('5') + int('7')
You should get the following output:
In this exercise, you have learned several ways in which strings work with casting.
The input() Function
The input()
function is a built-in function that allows user input. It's a little different than what we have seen so far. Let's see how it works in action.
Exercise 12: The input() Function
In this exercise, you will utilize the input()
function to obtain information from the user:
- Open a new Jupyter Notebook.
- Ask a user for their name. Respond with an appropriate greeting:
# Choose a question to ask print('What is your name?')
You should get the following output:
- Now, set a variable that will be equal to the
input()
function, as mentioned in the following code snippet:name = input()
You should get the following output:
- Finally, select an appropriate output:
print('Hello, ' + name + '.')
You should get the following output:
Note
input()
can be finicky in Jupyter Notebooks. If an error arises when entering the code, try restarting
the kernel. Restarting the kernel will erase the current memory and start each cell afresh. This is advisable if the notebook stalls.
In this exercise, you have learned how the input()
function works.
Activity 3: Using the input() Function to Rate Your Day
In this activity, you need to create an input type where you ask the user to rate their day on a scale of 1 to 10.
Using the input()
function, you will prompt a user for input and respond with a comment that includes the input. In this activity, you will print a message to the user asking for a number. Then, you will assign the number to a variable and use that variable in a second message that you display to the user.
The steps are as follows:
- Open a new Jupyter Notebook.
- Display a question prompting the user to rate their day on a number scale of
1
to10
. - Save the user's input as a variable.
- Display a statement to the user that includes the number.
Note
The solution for this activity can be found via this link.