1# f-strings are short for formatted string like the following
2# you can use the formatted string by two diffrent ways
3# 1
4name = "John Smith"
5print(f"Hello, {name}") # output = Hello, John Smith
6
7# 2
8name = "John Smith"
9print("Hello, {}".format(name)) # output = Hello, John Smith
10
1# If you want to use repr in f-string use "!r"
2# Normal behavior (using str)
3>>> color = "blue\ngreen"
4>>> day = datetime.date(2020, 6, 4)
5>>> f"Color is {color} and day is {day}"
6'Color is blue\ngreen and day is 2020-06-04'
7# Alternate behavior (using repr)
8>>> f"Color is {color!r} and day is {day!r}"
9"Color is 'blue\\ngreen' and day is datetime.date(2020, 6, 4)"
1# f-string is a format for printing / returning data
2# It helps you to create more consise and elegant code
3
4########### Example program ##############
5
6# User inputs their name (e.g. Michael Reeves)
7name = input()
8# Program welcomes the user
9print(f"Welcome to grepper {name}")
10
11################ Output ################
12
13""" E.g. Welcome to grepper Michael Reeves """
1>>> name = "Eric"
2>>> age = 74
3>>> f"Hello, {name}. You are {age}."
4'Hello, Eric. You are 74.'
5
1# This answer might be long, but it explains more python f-strings, how to use them and when to use them.
2# Python f-strings are used to write code faster.
3# Here is an example:
4name = "George"
5age = 16
6favorite_food = "pizza"
7
8# Instead of doing this:
9print("My name is", name, ", my age is", age, ", and my favorite food is", favorite_food)
10
11# Or this:
12print("My name is "+ name +", my age is "+ str(age)+ ", and my favorite food is "+ favorite_food)
13
14# You could do this:
15print(f"My name is {name}, my age is {age}, and my favorite food is {favorite_food}")
16
17# You see that the code looks a little cleaner, and as you start using f-strings you realize you write much faster.
18"""
19Why put the f before the string, you ask?
20Well if you didnt, the output would literally be {name} instead of the actual variable
21One more thing: this is fairly new and only works with python 3.6 and higher.
22"""
1num_01, num_02, num_03 = 1, 2, 3
2print(f"Numbers : {num_01}, {num_02}, {num_03}")
3
4"""
5>>> Numbers: 1, 2, 3
6"""