Skip to content

Commit 340ba16

Browse files
authored
Merge pull request #14 from practical-python-org/feature/tutorial-lvl01-ch05
Added Chapter 5 of Python Tutorial
2 parents 43fe7f6 + f898cdf commit 340ba16

3 files changed

Lines changed: 227 additions & 1 deletion

File tree

Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
---
2+
description: String concatenation and interpolation in Python
3+
---
4+
5+
# String Interpolation and Concatenation
6+
7+
We learned what the string data type was from our [third chapter](03-data-types-pt01.md). A quick
8+
recap: Strings are used to represent any textual data.
9+
10+
We also saw how adding two inputs resulted in a different output than we expected.
11+
12+
```py
13+
num1 = input("Enter the first number: ")
14+
num2 = input("Enter the second number: ")
15+
result = num1 + num2
16+
17+
print("The sum of", num1, "and", num2, "is", result)
18+
```
19+
20+
After running the program:
21+
22+
```text
23+
Enter the first number: 23
24+
Enter the second number: 12
25+
The sum of 23 and 12 is 2312
26+
```
27+
28+
We briefly touched on the fact that this was caused by _string concatenation_. In this chapter, we
29+
will look at what concatenation is, and at a more powerful way of combining text and variables
30+
called _string interpolation_.
31+
32+
## Why do we need this?
33+
34+
Most programs need to build sentences out of a mix of fixed text and changing data. For example,
35+
greeting a user by name, or showing a player's score. So far, the only way we've done this is by
36+
passing multiple values to `print`:
37+
38+
```python
39+
name = "Alan"
40+
age = 34
41+
42+
print("My name is", name, "and I am", age, "years old.")
43+
```
44+
45+
This works, but it only works with `print`. What if we want to, for example, store the full sentence
46+
in a variable instead? This is where concatenation and interpolation come in.
47+
48+
## String Concatenation
49+
50+
Concatenation simply means joining two or more strings together, one after the other. In Python, we
51+
can do this with the `+` operator.
52+
53+
```python
54+
first_name = "Alan"
55+
last_name = "Turing"
56+
57+
full_name = first_name + " " + last_name
58+
print(full_name)
59+
```
60+
61+
```text
62+
Alan Turing
63+
```
64+
65+
Notice that we added `" "` (a string containing a single space) in the middle. Concatenation joins
66+
strings _exactly_ as they are, so Python will not add any spaces for us. Without it, we would get
67+
`AlanTuring` as the output.
68+
69+
### Concatenating with other data types
70+
71+
Concatenation only works between strings. This means that if we try to join a string with a number,
72+
Python will raise an error:
73+
74+
```python
75+
name = "Alan"
76+
age = 34
77+
78+
print("My name is " + name + " and I am " + age + " years old.")
79+
```
80+
81+
```text
82+
TypeError: can only concatenate str (not "int") to str
83+
```
84+
85+
Python doesn't know whether `"I am " + 34` should mean "add" or "join", so instead of guessing, it
86+
stops with an error. To fix it, we need to convert the number to a string first. Remember type
87+
casting from the previous chapter? We can use the `str` function for this:
88+
89+
```python
90+
name = "Alan"
91+
age = 34
92+
93+
print("My name is " + name + " and I am " + str(age) + " years old.")
94+
```
95+
96+
```text
97+
My name is Alan and I am 34 years old.
98+
```
99+
100+
## String Interpolation
101+
102+
Interpolation is the process of inserting values directly into a string. Instead of breaking the
103+
string apart and gluing the pieces back together, we write the whole sentence at once and mark the
104+
places where the values should go. Python gives us two ways of doing this.
105+
106+
### f-strings
107+
108+
An f-string (short for _formatted string literal_) is a string with an `f` placed right before the
109+
opening quote. Inside it, anything wrapped in curly braces `{}` is replaced with its value.
110+
111+
```python
112+
name = "Alan"
113+
age = 34
114+
115+
print(f"My name is {name} and I am {age} years old.")
116+
```
117+
118+
```text
119+
My name is Alan and I am 34 years old.
120+
```
121+
122+
That's the same output as before, but much easier to read and write! Also notice that we didn't need
123+
to use `str(age)`. This is because f-strings convert the values for us automatically.
124+
125+
!!! warning
126+
127+
Don't forget the `f` before the quote! Without it, Python treats the string as normal text and
128+
prints the curly braces as-is: `My name is {name} and I am {age} years old.`
129+
130+
#### Expressions inside f-strings
131+
132+
You can put any valid Python expression (not just variable names) inside the curly braces, and
133+
Python will work out the result:
134+
135+
```python
136+
price = 20
137+
quantity = 3
138+
139+
print(f"Total cost: {price * quantity}")
140+
```
141+
142+
```text
143+
Total cost: 60
144+
```
145+
146+
#### Formatting values
147+
148+
You can also control how a value is displayed by adding a colon `:` followed by a format
149+
specification inside the braces. One of the most common uses of this is limiting the number of
150+
decimal places of a float:
151+
152+
```python
153+
pi = 3.14159265
154+
155+
print(f"Pi is roughly {pi:.2f}")
156+
```
157+
158+
```text
159+
Pi is roughly 3.14
160+
```
161+
162+
Here, `.2f` means "show this as a float with 2 digits after the decimal point".
163+
164+
### The `str.format()` method
165+
166+
Before f-strings were introduced in Python 3.6, the most common way to interpolate was the `format`
167+
method of strings. You will still see this in a lot of older code, so it is worth knowing.
168+
169+
Instead of placing the variables inside the string, you leave empty curly braces `{}` as
170+
placeholders, and pass the values to `.format()` afterwards. The values are filled in order like so:
171+
172+
```python
173+
name = "Alan"
174+
age = 34
175+
176+
print("My name is {} and I am {} years old.".format(name, age))
177+
```
178+
179+
```text
180+
My name is Alan and I am 34 years old.
181+
```
182+
183+
You can also number the placeholders to control which value goes where, or give them names:
184+
185+
```python
186+
# Using positions
187+
print("{1} is {0} years old.".format(age, name))
188+
189+
# Using names
190+
print("{n} is {a} years old.".format(n=name, a=age))
191+
```
192+
193+
!!! note
194+
195+
Anything after a `#` on a line is a comment. Comments are notes for humans reading the code, so
196+
Python ignores them completely.
197+
198+
It's output:
199+
200+
```text
201+
Alan is 34 years old.
202+
Alan is 34 years old.
203+
```
204+
205+
## Which one should I use?
206+
207+
All three approaches produce the same kind of result: a new string. Here's a quick comparison using
208+
the same example.
209+
210+
```python
211+
name = "Alan"
212+
age = 34
213+
214+
print("My name is " + name + " and I am " + str(age) + " years old.") # concatenation
215+
print("My name is {} and I am {} years old.".format(name, age)) # str.format()
216+
print(f"My name is {name} and I am {age} years old.") # f-string
217+
```
218+
219+
Here are some general rules for their usage.
220+
221+
- Use **f-string** interpolation for most situations. They are the shortest, the most readable, and
222+
the most common way to write modern Python.
223+
- Use **concatenation (+)** for simple cases where you want to join two strings only.
224+
- **`str.format()`** when you are reading older code.

‎docs/python-tutorial/chapters/index.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ in-depth Python features.
1212
- [Brief Python History](01-python-history.md)
1313
- [Introduction to Variables](02-intro-to-variables.md)
1414
- [Data Types pt 1 (`string`, `int`, `float` & `bool`)](03-data-types-pt01.md)
15-
- [Builtin Functions pt 1 (`print` & `input` and type casting)](04-built-in-functions-pt01.md)
15+
- [Builtin Functions pt 1 (`print`, `input` & type casting)](04-built-in-functions-pt01.md)
16+
- [String Interpolation & Concatenation (f-strings, `str.format` & `+`)](05-string-functions.md)
1617
- String Interpolation & Concatenation (f-strings, str.format & +)
1718
- Operators pt 1 (Comparison & Arithmetic)
1819
- Conditional Statements (`if`, `else` & `elif`)

‎zensical.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ nav = [
2525
"python-tutorial/chapters/02-intro-to-variables.md",
2626
"python-tutorial/chapters/03-data-types-pt01.md",
2727
"python-tutorial/chapters/04-built-in-functions-pt01.md",
28+
"python-tutorial/chapters/05-string-functions.md",
2829
] },
2930
{ "Resources" = [
3031
"resources/index.md",

0 commit comments

Comments
 (0)