.format method in python code example
Example 1: python string format
string_a = "Hello"
string_b = "Cena"
# Index based:
print("{0}, John {1}"
.format(string_a, string_b))
# Object based:
print("{greeting}, John {last_name}"
.format(greeting=string_a, last_name=string_b))
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
print("My name is {0} and I am {1} years old".format(name, age))
Example 4: python string format
'{} {}'.format('one', 'two')