1# Newer f-string format
2name = "Foo"
3age = 12
4print(f"Hello, My name is {name} and I'm {age} years old.")
5# output :
6# Hello, my name is Foo and I'm 12 years old.
1# There are 3 different types of formatting.
2>>> name = "John"
3>>> age = 19
4>>> language = "python"
5>>> print(f"{name} of age {age} programs in {language}") # Commonly used.
6John of age 19 programs in python
7>>> print("%s of age %d programs in %s" %(name, age, language)) # %s for str(), %d for int(), %f for float().
8John of age 19 programs in python
9>>> print("{} of age {} programs in {}".format(name, age, language)) # Values inside .format() will be placed inside curly braces repectively when no index is specified.
10John of age 19 programs in python
11>>> print("{2} of age {1} programs in {0}".format(name, age, language)) # Index can be specified inside of curly braces to switch the values from .format(val1, val2, val3).
12python of age 19 programs in John
1string_a = "Hello"
2string_b = "Cena"
3
4# Index based:
5print("{0}, John {1}"
6 .format(string_a, string_b))
7# Object based:
8print("{greeting}, John {last_name}"
9 .format(greeting=string_a, last_name=string_b))
10
1Name = 'Tame Tamir'
2Age = 14
3
4Formatted_string = 'Hello, my name is {name}, I am {age} years old.'.format(name=Name,age=Age)
5# after the formatting, the variable name inside the {} will be replaced by whatever you declare in the .format() part.
6print(Formatted_string) # output = Hello, my name is Tame Tamir, I am 14 years old.
1#The {} are replaced by the vairables after .format
2new_string = "{} is string 1 and {} is string 2".format("fish", "pigs")
1print('The {2} {1} {0}'.format('fox', 'brown', 'quick'))
2
3result = 100/777
4
5print('{newvar}'.format(newvar = result))
6
7print('the result was {r:0.3f}'.format(r = result))