python string formatting code example
Example 1: f string in python
# 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
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 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 4: 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 5: python format specifier
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
Example 6: python string format
print("My name is {0} and I am {1} years old".format(name, age))