|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "Fstring, yet another string formatter in Python" |
| 4 | +date: "2019-01-14 20:52:03 +0530" |
| 5 | +tag: |
| 6 | + - fstring |
| 7 | + - Python |
| 8 | + - Python3.6 |
| 9 | + - FormattedStrings |
| 10 | +--- |
| 11 | + |
| 12 | + |
| 13 | +Fstring is a cool feature introduced as a part of Python 3.6. Fstring can be |
| 14 | +elaborated as "Formatted String". At the time of writing this post, Python |
| 15 | +already has more than two ways to a format string. Still, Fstring is released by |
| 16 | +giving yet another way to format a string. Fstrings can be easy to understand |
| 17 | +and simple to read. When you prefix the string with ```f```, it becomes a |
| 18 | +formatted string. All names wrapped inside the curly braces ({}) are resolved |
| 19 | +with the value of variable available in local scope. If the variable isn’t found |
| 20 | +in the local scope then it will raise a ```NameError``` exception. |
| 21 | + |
| 22 | + |
| 23 | +### Demonstration |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +Below is the code used in the example |
| 28 | + |
| 29 | +```python |
| 30 | +name = "Jay" |
| 31 | +print(f"Hello {name}") |
| 32 | +``` |
| 33 | + |
| 34 | +[ TODO: Find, Are there any tool avilable to convert all a formatted strings to |
| 35 | +Fstrings?] |
| 36 | + |
| 37 | +In my view, this option of string formation is more concise and readable than |
| 38 | +all other options. I advise migrating your code to Fstrings if your Python |
| 39 | +interpreter is greater than or equal to version 3.6. You should note that |
| 40 | +existing string formation approaches are still supported and are not subject to |
| 41 | +depreciate in the near future. |
| 42 | + |
| 43 | + |
| 44 | +### Summary |
| 45 | + |
| 46 | + |
| 47 | +* Fstring can be elaborated as "Formatted String". |
| 48 | + |
| 49 | +* Variable is always resolved at local scope. If it isn't found then it will |
| 50 | + rise the ```NameError``` exception. |
| 51 | + |
| 52 | +* You can format your strings by Fstring approach only if your Python |
| 53 | + interpreter version is greater than or equal to 3.6. |
| 54 | + |
| 55 | +* Existing string formation approches are not subjected to depricate soon. |
0 commit comments