Python String Example | Format a String using F-Strings

This python string example will shows us how to format a python string using f-strings.

In order to use F-string in python, we should understand:

  • How to create a F-string in python?
  • How to format a string based on F-string?

We will use an example to answer this question.

For example:

name = 'NoteHope'
year = 2014
string = f'{name} was started in {year}'
print(string)

string = f'{name} was started in {2013 + 1}.'
print(string)

yw = {'name': 'YoungWonks', 'year': 2014}
string = f"{yw['name']} was started in {yw['year']}."
print(string)

Run this code, we will get:

NoteHope was started in 2014 
NoteHope was started in 2014.
NoteHope was started in 2014.

From example above, we can find:

  • We can use f”text” to create a F-string in python.
  • We can use {} to format a string based on F-string.