Browse Source

Mentioning named parameters in string formatting + f-strings.

Fixes #69
Swaroop C H 7 years ago
parent
commit
54fde3d813
1 changed files with 24 additions and 0 deletions
  1. 24 0
      basics.md

+ 24 - 0
basics.md

@@ -141,6 +141,30 @@ print('Why is {} playing with that python?'.format(name))
 
 which will give the same exact output as the previous program.
 
+We can also name the parameters:
+
+```python
+age = 20
+name = 'Swaroop'
+
+print('{name} was {age} years old when he wrote this book'.format(name=name, age=age))
+print('Why is {name} playing with that python?'.format(name=name))
+```
+
+which will give the same exact output as the previous program.
+
+Python 3.7 introduced a shorter way to do named parameters, called "f-strings":
+
+```python
+age = 20
+name = 'Swaroop'
+
+print(f'{name} was {age} years old when he wrote this book')  # notice the 'f' before the string
+print(f'Why is {name} playing with that python?')  # notice the 'f' before the string
+```
+
+which will give the same exact output as the previous program.
+
 What Python does in the `format` method is that it substitutes each argument value into the place of the specification. There can be more detailed specifications such as:
 
 ```python