Here are four ways to format the string in Python:
Method 1: Old Style (% Operator)
This is the traditional method of string formatting, inspired by C’s printf syntax.
It uses % as a placeholder for values.
Example
substitute = "Homer"
print("Yello %s" % substitute)
print("Yello %s %s" % (substitute, 'simpson'))
Output
Yello Homer
Yello Homer simpson
Method 2: Using format() method
The string.format() method is more powerful and flexible.
It uses curly braces {} as placeholders.
Example
string = "Homer"
print("Yello {}".format(string))
Output
Yello Homer
Method 3: Using f-strings()
To create an f-string, prefix the string with the letter “f or F”.
F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.
Example
sub1 = "Yello"
sub2 = "Simpson"
print(f"{sub1} Homer {sub2}")
Output
Yello Homer Simpson
Method 4: Using Template Strings
The string.Template class offers a less commonly used mechanism for string formatting.
It’s useful in situations where you need to format strings from user-supplied data, and you want to avoid security issues related to the evaluation of string expressions.
from string import Template
greeting_template = Template('Yello $name Simpson')
formatted_string = greeting_template.substitute(name="Homer")
print(formatted_string)
Output
Yello Homer Simpson