spelling corrections and example addition (#21268)

This commit is contained in:
Roppon Picha
2018-11-08 21:36:17 +07:00
committed by Tom
parent 3abf1f69b7
commit 2057069f2c

View File

@ -2,9 +2,9 @@
title: Python f-strings
---
# f-strings in Python
In Python version 3.6, a new method of formatting strings was implemented. The new method is called Literal string interpolation (though commonly referred to as an f-string).
In Python version 3.6, a new method of formatting strings was implemented. The new method is called Literal string interpolation (though commonly referred to as an f-string, due to f prefix at the beginning of the string).
The use of f-string allows the programmer to dynamically insert a variable into a string in a clean and concise manner. In addition to inserting variables into a string this feature also also provides the ability for a programmer to evaluate expressions, join the contents of collection, and even invoke functions within the f-string.
The use of f-string allows the programmer to dynamically insert a variable into a string in a clean and concise manner. In addition to inserting variables into a string this feature also provides the ability for a programmer to evaluate expressions, join the contents of collection, and even invoke functions within the f-string.
To perform these dynamic behaviours within an f-string we wrap them inside curly brackets within the string, and prepend a lower case f to the beginning of the string (before the opening quote).
@ -15,14 +15,30 @@ To perform these dynamic behaviours within an f-string we wrap them inside curly
```python
name = 'Jon Snow'
greeting = f'Hello! {name}'
greeting = f'Hello! {name}.'
print(greeting)
```
#### Output
```
Hello! Jon Snow
Hello! Jon Snow.
```
### Multiple variables, of different types, can be inserted in the same string:
### Input
```python
item_id = 'P12305'
price = 425.50
print(f'Item {item_id} costs {price} USD.')
```
#### Output
```
Item P12305 costs 425.50 USD.
```
### Evaluate an expression in a string: