Skip to content

Commit ced12fe

Browse files
committed
Adds f-strings properly
1 parent 924d3c3 commit ced12fe

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

docs/variablesanddatatypes.rst

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -225,14 +225,36 @@ This is my preferable way to format strings. Example below:
225225
::
226226

227227
>>> name = "Kushal"
228-
>>> org = "dgplug"
229-
>>> number_of_years = 10
230-
>>> msg = "{0} is part of all {1} years of {2} summer training".format(name, number_of_years, org)
228+
>>> language = "Python"
229+
>>> msg = "{0} loves {1}.".format(name, language)
231230
>>> print(msg)
232-
Kushal is part of all 10 years of dgplug summer training
231+
Kushal loves Python.
233232

234-
From Python 3.6 we can also do like below::
233+
In Python 3.6, we have a new way to do string formatting. `PEP 498
234+
<https://www.python.org/dev/peps/pep-0498/>`_ introduces the concept called
235+
**f-strings**.
235236

236-
>>> msg = f"{name} is part of all {number_of_years} years of {org} summer training"
237+
Here is the same example using *f-strings*::
238+
239+
>>> name = "Kushal"
240+
>>> language = "Python"
241+
>>> msg = f"{name} loves {language}."
237242
>>> print(msg)
238-
Kushal is part of all 10 years of dgplug summer training
243+
Kushal loves Python.
244+
245+
F-strings provide a simple and readable way to embed Python expressions in a
246+
string. Here are a few more examples.
247+
248+
::
249+
250+
>>> answer = 42
251+
>>> print(f"The answer is {answer}")
252+
The answer is 42
253+
>>> import datetime
254+
>>> d = datetime.date(2004, 9, 8)
255+
>>> f"{d} was a {d:%A}, we started the mailing list back then."
256+
'2004-09-08 was a Wednesday, we started the mailing list back then.'
257+
258+
If you want to know more about how this feature came into Python, watch this
259+
`talk <https://www.youtube.com/watch?v=M4w4wKveVo4>`_ from `Mariatta Wijaya
260+
<https://twitter.com/mariatta>`_.

0 commit comments

Comments
 (0)