There are several ways to format strings correctly.
Using the %
operator
name = "Alice" age = 30 formatted_string = "My name is %s and I am %d years old." % (name, age) print(formatted_string) # Output: My name is Alice and I am 30 years old.
Using str.format()
method
name = "Alice" age = 30 formatted_string = "My name is {} and I am {} years old.".format(name, age) print(formatted_string) # Output: My name is Alice and I am 30 years old.
Using f-strings
(formatted string literals) (Python 3.6+
)
name = "Alice" age = 30 formatted_string = f"My name is {name} and I am {age} years old." print(formatted_string) # Output: My name is Alice and I am 30 years old.
Using template strings with string.Template
name = "Alice" age = 30 from string import Template template = Template("My name is $name and I am $age years old.") formatted_string = template.substitute(name=name, age=age) print(formatted_string) # Output: My name is Alice and I am 30 years old.
Using concatenation with +
operator
name = "Alice" age = 30 formatted_string = "My name is " + name + " and I am " + str(age) + " years old." print(formatted_string) # Output: My name is Alice and I am 30 years old.
Using join
method
name = "Alice" age = 30 formatted_string = " ".join(["My name is", name, "and I am", str(age), "years old."]) print(formatted_string) # Output: My name is Alice and I am 30 years old.
Using printf-style
formatting with dictionary
name = "Alice" age = 30 data = {"name": name, "age": age} formatted_string = "My name is %(name)s and I am %(age)d years old." % data print(formatted_string) # Output: My name is Alice and I am 30 years old.
Using str.format_map
with dictionary
name = "Alice" age = 30 formatted_string = "My name is {name} and I am {age} years old.".format_map(data) print(formatted_string) # Output: My name is Alice and I am 30 years old.
These methods cover the most common ways to format strings in Python, each useful in different contexts and versions of Python.