f string python syntax code example
Example 1: f string in python
# f-strings are short for formatted string like the following
# you can use the formatted string by two diffrent ways
# 1
name = "John Smith"
print(f"Hello, {name}") # output = Hello, John Smith
# 2
name = "John Smith"
print("Hello, {}".format(name)) # output = Hello, John Smith
Example 2: python fstring
#python3.6 is required
age = 12
name = "Simon"
print(f"Hi! My name is {name} and I am {age} years old")
Example 3: python f string literal
# This answer might be long, but it explains more python f-strings, how to use them and when to use them.
# Python f-strings are used to write code faster.
# Here is an example:
name = "George"
age = 16
favorite_food = "pizza"
# Instead of doing this:
print("My name is", name, ", my age is", age, ", and my favorite food is", favorite_food)
# Or this:
print("My name is "+ name +", my age is "+ str(age)+ ", and my favorite food is "+ favorite_food)
# You could do this:
print(f"My name is {name}, my age is {age}, and my favorite food is {favorite_food}")
# You see that the code looks a little cleaner, and as you start using f-strings you realize you write much faster.
"""
Why put the f before the string, you ask?
Well if you didnt, the output would literally be {name} instead of the actual variable
One more thing: this is fairly new and only works with python 3.6 and higher.
"""
Example 4: python f-strings
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
'January 27, 2017'
>>> f"{today=:%B %d, %Y}" # using date format specifier and debugging
'today=January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
'0x400'
>>> foo = "bar"
>>> f"{ foo = }" # preserves whitespace
" foo = 'bar'"
>>> line = "The mill's closed"
>>> f"{line = }"
'line = "The mill\'s closed"'
>>> f"{line = :20}"
"line = The mill's closed "
>>> f"{line = !r:20}"
'line = "The mill\'s closed" '
Example 5: python f string
>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'