-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfstrings.qmd
More file actions
34 lines (23 loc) · 1.18 KB
/
fstrings.qmd
File metadata and controls
34 lines (23 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
---
filters:
- pyodide
---
# Variables and Printing together - the fString
{{< video https://youtu.be/vhNTM_MQFP8 >}}
Python has a rather neat type of string called an fString. These are strings where we can include formatting within the string to define where we want dynamic text.
We often want to do this where we want to insert the value of a variable into a string of text.
e.g. “Her name is <<insert name here>>”
To use fStrings, we simply put the character f immediately before our opening quotation mark, and use curly brackets to denote where we want to include the name of a variable, so that Python will pull in the value in that variable instead of hard-coded text.
Example :
```{pyodide-python}
name_of_user = "Dan"
print(f"Hello {name_of_user}!")
```
We can also do some other cool things with fStrings. We’re not restricted to just variable names either, we can put in the curly brackets any instruction whose output will result in something that can be interpreted as a string (ie some characters).
```{pyodide-python}
print(f"The answer is {2+2}")
```
```{pyodide-python}
my_float = 3.1415926535
print(f"My number rounded to 3 decimal places is {my_float:.3f}")
```