xxxxxxxxxx
# f-string is a format for printing / returning data
# It helps you to create more consise and elegant code
########### Example program ##############
# User inputs their name (e.g. Michael Reeves)
name = input()
# Program welcomes the user
print(f"Welcome to grepper {name}")
################ Output ################
""" E.g. Welcome to grepper Michael Reeves """
xxxxxxxxxx
# 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
xxxxxxxxxx
>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'
xxxxxxxxxx
#python3.6 is required
age = 12
name = "Simon"
print(f"Hi! My name is {name} and I am {age} years old")
xxxxxxxxxx
print(f"|{variable:25}|") #normal
print(f"|{variable:<25}|") # left align
print(f"|{variable:>25}|") # right align
print(f"|{variable:^25}|\n") #middle align
print(f"Using Numeric {variable = }")
print(f"With two decimal places: {variable:.2f}")
print(f"With four decimal places: {variable:.4f}")
print(f"With two decimal places and a comma: {variable:,.2f}")
### credit to http://cissandbox.bentley.edu/sandbox/wp-content/uploads/2022-02-10-Documentation-on-f-strings-Updated.pdf
xxxxxxxxxx
>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'
xxxxxxxxxx
#f string can be used insted of + in print statments
age = 33
#instead of:
print("I am " + str(age)) #output: I am 33
#do this
print(f"I am {age}") #output: I am 33
xxxxxxxxxx
# f-strings help in string concatenation
name = 'Psych4_3.8.3'
age = 23
job = 'programmer'
#USING OLD METHOD
print("I am %s a %t of age %u", %(name, job, age))
# USING F-STRING
print(f"I am {name} a {job} of age {age}")
# here you can even see whcih value is inserted in which place....
# the f means that it is an f string. DONT FORGET IT!!
xxxxxxxxxx
# Ques.1
num = int(input("Enter your number: "))
for i in range(1, 11):
# print(str(num) + " × " + str(i) + " = " + str(i*num))
# you can't add variables
print(f"{num} × {i} = {num*i}")
# you can add variables
xxxxxxxxxx
>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."