In addition to processing, strings are also often used to beautify the output of your program, this generally includes the formatting of variables. Python provides multiple ways of achieving this.
We can also combine strings with variables in several ways. The most intuitive being the concatenation of strings and variables using the #\color{#3e999f} {\mathtt{\text{+}}}# operator:
>>> var = "world" >>> "Hello, " + var + "!"
|
'Hello, world!'
|
If the variable is not already a string, we need to cast it to #\color{#4271ae} {\mathtt{\text{str}}}# before adding it to the string using #\color{#4271ae} {\mathtt{\text{str}}}\mathtt{\text{()}}#.
>>> var = 12 >>> "I have " + str(var) + " eggs."
|
'I have 12 eggs.'
|
When using multiple variables, this gets messy very quickly. Furthermore, the open spaces at the end or beginning of strings to make the punctuation work is not very stylish. Luckily, Python has got us covered; it provides several more concise formatting options.
Python provides the #\color{#4271ae} {\mathtt{\text{format}}} \mathtt{\text{()}}# method for strings, which allows us to include one or multiple variables in the string directly. #\color{#4271ae} {\mathtt{\text{format}}} \mathtt{\text{()}}# can be used with any of the discussed declaration methods above.
\[\color{#718c00} {\mathtt{"} \textbf{. . .}}\{:\textit{format}_\textit{1}\}\color{#718c00}{\textbf{. . .}}\{:\textit{format}_\textit{2}\}\color{#718c00}{\textbf{. . .}\mathtt{"}}.\color{#4271ae} {\mathtt{format}}(\textit{object}_\textit{1}, \textit{object}_\textit{2}, \text{. . .} )\]
Where object can be of any type and format is any of the standard formatting options.
An example of #\color{#4271ae} {\mathtt{\text{str}}}# objects as arguments, without specific formatting.
>>> subj = "he" >>> obj = "me" >>> "That's when {} came to {}.".format(subj, obj)
|
"That's when he came to me."
|
However, this is not very explicit when using multiple variables and thus bad practice. The better practice would be to either include reference by position or name. When using explicit name references in your formatting options, the order of arguments in the #\mathtt{\color{#4271ae} {\text{format}}}\mathtt{\text{()}}# call doesn't have to match.
>>> subj = "he" >>> obj = "me" >>> "That's when {0} came to {1}.".format(subj, obj)
|
"That's when he came to me."
|
>>> "That's when {subj} came to {obj}.".format(subj="he", obj="me")
|
"That's when he came to me."
|
Using explicit references also allows you to access the attributes or methods of your arguments.
>>> var = "This is a string." >>> "The first character in the string is '{0[0]}'.".format(var)
|
"The first character in the string is 'T'."
|
There is a formatting option to cut strings after a certain amount of characters, which can be handy for more compact output.
>>> var = "This is the first sentence of a longer paragraph. This is the second sentence." >>> 'var = "{:.20s}..."'.format(var)
|
'var = "This is the first se..."'
|
Formatting options are particularly interesting when using numbers, they allow you to quickly transform numbers into more readable formats:
>>> pi = 3.141592653593 >>> "The ratio of a circle's circumference to its diameter is approximately {:.2f}.".format(pi)
|
"The ratio of a circle's circumference to its diameter is approximately 3.14."
|
>>> var = 31536000 >>> "There are {:g} seconds in a year.".format(var)
|
"There are 3.1536e+07 seconds in a year."
|
>>> var = 85 >>> "{binary:b} is {integer} in binary.".format(binary=var, integer=var)
|
'1010101 is 85 in binary.'
|
>>> var = 0.15 >>> "{decimal} is {percent:.0%}.".format(decimal=var, percent=var)
|
'0.15 is 15%.'
|
Python 3.6 introduced an even more concise way of string formatting: f-strings, named after the #\color{#718c00} {\mathtt{\text{f}}}# that precedes the string. F-strings allow direct embedding of expressions and references within the string without an additional #\color{#4271ae} {\mathtt{\text{format}}}\mathtt{\text{()}}# call. This is also inherently more explicit and thus better practice. Like #\color{#4271ae} {\mathtt{\text{format}}}\mathtt{\text{()}}#, f-strings can be used with any of the discussed quote types.
\[\color{#718c00} {\mathtt{f"}\textbf{. . .}}\{\textit{expression}_\textit{1}:\textit{format}_\textit{1}\}\color{#718c00}{\textbf{. . .}}\{\textit{expression}_\textit{2}:\textit{format}_\textit{2}\}\color{#718c00}{\textbf{. . .}\mathtt{"}}\]
Where expression can be any valid Python expression and format is any of the standard formatting options.
Let's take a look at an example of #\color{#4271ae} {\mathtt{\text{format}}}\mathtt{\text{()}}# and an f-string that result in the same output:
>>> var = 31536000 >>> "There are {:g} seconds in a year.".format(var)
|
"There are 3.1536e+07 seconds in a year."
|
>>> var = 31536000 >>> f"There are {var:g} seconds in a year."
|
"There are 3.1536e+07 seconds in a year."
|
Note that the two methods are very similar, but instead of no reference or a reference to an argument of the #\color{#4271ae} {\mathtt{\text{format}}}\mathtt{\text{()}}# function we can directly reference the variable.
>>> var = 85 >>> f"{var:b} is {var} in binary."
|
"1010101 is 85 in binary."
|
As opposed to #\color{#4271ae} {\mathtt{\text{format}}}\mathtt{\text{()}}#, f-strings also allow direct embedding of expressions, such as function calls or arithmetic, which are then evaluated before the result is displayed.
>>> f"8 divided by 4 equals {8 // 2}."
|
'8 divided by 4 equals 2.'
|