From 0318c8c33b38bd8ef214ba8fea059bdb97836f3f Mon Sep 17 00:00:00 2001 From: Once Date: Mon, 8 Oct 2018 20:36:35 +0800 Subject: [PATCH] Added f-string samples to string-formatting --- tutorial/string-formatting.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/tutorial/string-formatting.md b/tutorial/string-formatting.md index 3851915..50e667e 100755 --- a/tutorial/string-formatting.md +++ b/tutorial/string-formatting.md @@ -1,7 +1,6 @@ Formatting strings and output ============================== -Examples in Python 3 - +str.format() in Python 3 ```python """ @@ -31,8 +30,25 @@ print("{0:10}{1:10}".format("Hello", "World")) ``` +f-string formatting in Python 3 +```python +""" +Python 3.6 added support for new kind of formatting. +""" +# The syntax is similar to the one you used with str.format() but less verbose and also faster. +name = "John" +f"Hello, {name}" +# F-strings are evaluated at runtime, you can put any and all valid Python expressions in them. +f"1 + 1 = {1+1}" +# You could also call functions +def to_lowercase(string): + return string.lower() + +f"My name is {to_lowercase("John")} at lower-case" + +``` Reference and read more ------------------------------