Add input and output for code examples (#18646)

This commit is contained in:
Lachlan Eagling
2018-10-13 18:25:07 +11:00
committed by Aditya
parent 721f799f28
commit 1d0c7f3f8b

View File

@ -8,39 +8,72 @@ The use of f-string allows the programmer to dynamically insert a variable into
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. 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.
### Examples ## Examples
1. Dynamically inserting a variable into a string at runtime: ### Dynamically inserting a variable into a string at runtime:
```python
name = 'Jon Snow'
greeting = f'Hello! {name}'
print(greeting)
```
2. Evaluate an expression in a string: #### Input
```python
val1 = 2 ```python
val2 = 3 name = 'Jon Snow'
expr = f'The sum of {val1} + {val2} is {val1 + val2}' greeting = f'Hello! {name}'
print(expr) print(greeting)
``` ```
3. Calling a function and inserting output within a string:
```python #### Output
def sum(*args):
```
Hello! Jon Snow
```
### Evaluate an expression in a string:
#### Input
```python
val1 = 2
val2 = 3
expr = f'The sum of {val1} + {val2} is {val1 + val2}'
print(expr)
```
#### Output
```
The sum of 2 + 3 is 5
```
### Calling a function and inserting output within a string:
#### Input
```python
def sum(*args):
result = 0 result = 0
for arg in args: for arg in args:
result += arg result += arg
return result return result
func = f'The sum of 3 + 5 is {sum(3, 5)}' func = f'The sum of 3 + 5 is {sum(3, 5)}'
print(func) print(func)
``` ```
4. Joining the contents of a collection within a string:
```python #### Output
fruits = ['Apple', 'Banana', 'Pear'] ```
The sum of 3 + 5 is 8
```
### Joining the contents of a collection within a string:
#### Input
```python
fruits = ['Apple', 'Banana', 'Pear']
list_str = f'List of fruits: {", ".join(fruits)}'
print(list_str)
```
#### Output
```
List of fruits: Apple, Banana, Pear
```
list_str = f'List of fruits: {", ".join(fruits)}'
print(list_str)
```
### Sources ### Sources
https://www.python.org/dev/peps/pep-0498/ https://www.python.org/dev/peps/pep-0498/