String Formatting
String formatting is a way to create formatted strings in Python, allowing you to insert variables, expressions, or other strings into a larger string.
Using the %
Operator
One common method of string formatting in Python is using the %
operator. For example, to insert a variable into a string:
name = 'Alice'
age = 30
message = 'Hello, %s! You are %d years old.' % (name, age)
print(message)
Output:Hello, Alice! You are 30 years old.
Using the format()
Method
Another method of string formatting is using the format()
method. This method allows for more flexibility and readability. For example:
name = 'Alice'
age = 30
message = 'Hello, {}! You are {} years old.'.format(name, age)
print(message)
Output:Hello, Alice! You are 30 years old.
Using F-Strings (Python 3.6+)
In Python 3.6 and later versions, you can use f-strings for string formatting, which provide a more concise and readable syntax:
name = 'Alice'
age = 30
message = f'Hello, {name}! You are {age} years old.'
print(message)
Output:Hello, Alice! You are 30 years old.
Conclusion
String formatting in Python allows you to create formatted strings easily and efficiently. By using the %
operator, format()
method, or f-strings, you can insert variables and expressions into strings to create dynamic and readable output.