.format python 3 code example

Example 1: python format float

>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True

Example 2: formatted string python

# Newer f-string format
name = "Foo"
age = 12
print(f"Hello, My name is {name} and I'm {age} years old.")
# output :
# Hello, my name is Foo and I'm 12 years old.

Example 3: python .format

Name = 'Tame Tamir'
Age = 14

Formatted_string = 'Hello, my name is {name}, I am {age} years old.'.format(name=Name,age=Age)
# after the formatting, the variable name inside the {} will be replaced by whatever you declare in the .format() part.
print(Formatted_string) # output = Hello, my name is Tame Tamir, I am 14 years old.

Example 4: python format specifier

from datetime import datetime

'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))

Example 5: str.format python 3

print("Sammy the {pr} {1} a {0}.".format("shark", "made", pr = "pull request"))

Example 6: .format python 3

#New Style
'{} {}'.format('one', 'two')

#Old Style
'%s %s' % ('one', 'two')