f prefix string python code example
Example 1: f string repr
# If you want to use repr in f-string use "!r"
# Normal behavior (using str)
>>> color = "blue\ngreen"
>>> day = datetime.date(2020, 6, 4)
>>> f"Color is {color} and day is {day}"
'Color is blue\ngreen and day is 2020-06-04'
# Alternate behavior (using repr)
>>> f"Color is {color!r} and day is {day!r}"
"Color is 'blue\\ngreen' and day is datetime.date(2020, 6, 4)"
Example 2: python f string
"""
An f-string stands for 'function-string' it's just used to work with
strings more appropiately, they do the exact same job as concantenating
strings but are more efficient and readable.
"""
# Concantenating strings:
Age = "25"
print("I am "+Age+" years old.")
# Using f strings:
Age = 25
print(f"I am {Age} years old.")
# ^ notice the letter 'f' at the begining of the string.
# That defines the string as being an f-string.
# A third way of inputting variables into a string is by using
# .format()
Age = "25"
print("I am {} years old.".format(Age))
# If you had more than one variable:
Age = "25"
Name = "Jeff"
print("I am {} years old, and my name is {}.".format(Age,Name))
Example 3: format specificer f strings python
#!/usr/bin/env python3
val = 12.3
print(f'{val:.2f}')
print(f'{val:.5f}')