string formatting python example

Example 1: 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 2: formatting in python

# There are 3 different types of formatting. 
>>> name = "John"
>>> age = 19
>>> language = "python"
>>> print(f"{name} of age {age} programs in {language}") # Commonly used.
John of age 19 programs in python
>>> print("%s of age %d programs in %s" %(name, age, language)) # %s for str(), %d for int(), %f for float().
John of age 19 programs in python
>>> print("{} of age {} programs in {}".format(name, age, language)) # Values inside .format() will be placed inside curly braces repectively when no index is specified.
John of age 19 programs in python
>>> 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).
python of age 19 programs in John

Example 3: python string format

'{} {}'.format('one', 'two')

Example 4: formatted string in python

>>> name = "world"
>>> print(f"Hello {name}!)"
'Hello world!'