How to format strings in python?
Python offers several ways to format strings, including the older %
operator method and the newer str.format()
and f-string methods.
Example using % operator:
name = 'John'
age = 30
result = 'My name is %s and I am %d years old.' % (name, age)
Solution using str.format():
result = 'My name is {} and I am {} years old.'.format(name, age)
Solution using f-string (Python 3.6+):
result = f'My name is {name} and I am {age} years old.'