Add input and output for code examples (#18646)
This commit is contained in:
@ -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.
|
||||
|
||||
### Examples
|
||||
1. Dynamically inserting a variable into a string at runtime:
|
||||
```python
|
||||
name = 'Jon Snow'
|
||||
greeting = f'Hello! {name}'
|
||||
print(greeting)
|
||||
```
|
||||
## Examples
|
||||
### Dynamically inserting a variable into a string at runtime:
|
||||
|
||||
2. Evaluate an expression in a string:
|
||||
```python
|
||||
val1 = 2
|
||||
val2 = 3
|
||||
expr = f'The sum of {val1} + {val2} is {val1 + val2}'
|
||||
print(expr)
|
||||
```
|
||||
3. Calling a function and inserting output within a string:
|
||||
```python
|
||||
def sum(*args):
|
||||
result = 0
|
||||
for arg in args:
|
||||
result += arg
|
||||
return result
|
||||
#### Input
|
||||
|
||||
func = f'The sum of 3 + 5 is {sum(3, 5)}'
|
||||
print(func)
|
||||
```
|
||||
4. Joining the contents of a collection within a string:
|
||||
```python
|
||||
name = 'Jon Snow'
|
||||
greeting = f'Hello! {name}'
|
||||
print(greeting)
|
||||
```
|
||||
|
||||
```python
|
||||
fruits = ['Apple', 'Banana', 'Pear']
|
||||
#### Output
|
||||
|
||||
```
|
||||
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
|
||||
for arg in args:
|
||||
result += arg
|
||||
return result
|
||||
|
||||
func = f'The sum of 3 + 5 is {sum(3, 5)}'
|
||||
print(func)
|
||||
```
|
||||
|
||||
#### Output
|
||||
```
|
||||
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
|
||||
https://www.python.org/dev/peps/pep-0498/
|
||||
|
Reference in New Issue
Block a user