1. Using f-string (formatted string literals).
Python f-strings provide a concise and readable way to embed expressions inside string literals, using curly braces `{}`.
def use_f_strings(): # Using f-strings language = "Python" rank = 1 print(f"{language} is number {rank}!") name = "Alice" age = 30 formatted_string = f"Name: {name}, Age: {age}" print(formatted_string) if __name__ == "__main__": use_f_strings()
2. Using `str.format()` method.
The `str.format()` method allows for more complex string formatting and is available in all versions of Python starting from 2.7.
def use_str_format(): language = "Python" rank = 1 # Using str.format() print("{} is number {}!".format(language, rank)) print("{language} is number {number}!".format(language="Python", number=1)) # Output: Python is number 1! name = "Bob" age = 25 formatted_string = "Name: {}, Age: {}".format(name, age) print(formatted_string) if __name__ == "__main__": use_str_format()
3. Using `string.Template`.
The `string.Template` class in the `string` module provides a way to substitute values into strings using placeholders.
from string import Template def use_string_template(): name = "Carol" age = 35 template = Template("Name: $name, Age: $age") formatted_string = template.substitute(name=name, age=age) print(formatted_string) if __name__ == "__main__": use_string_template()
Each of these methods has its own use case, with f-strings being the most concise and readable for most modern Python code, `str.format()` offering flexibility for complex formatting needs, and `string.Template` providing a straightforward option for situations requiring simpler and safer substitution (e.g., when dealing with user-provided templates).