How To Use String Formatters in Python 3

Published on Aug. 22, 2023, 12:16 p.m.

To format strings in Python 3, you can use string formatters which allow you to include variables or expressions inside a string. Here are some examples using the .format() method for string formatting:

# Basic string formatting with positional arguments
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 25 years old.

# String formatting with named arguments
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))
# Output: My name is Bob and I am 30 years old.

# String formatting with expressions
num = 10
print("The result is {}".format(num ** 2))
# Output: The result is 100.

You can also format numbers and strings in a specific way using format specifiers. Here are some examples:

# Formatting numbers with specific precision
pi = 3.14159
print("{:.2f}".format(pi))
# Output: 3.14

# Padding strings with spaces
text = "hello"
print("{:<10}".format(text))
# Output: 'hello     '

# Truncating strings
text = "This is a very long string"
print("{:.5}".format(text))
# Output: 'This '

# Using f-strings (Python 3.6+)
name = "Charlie"
age = 35
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Charlie and I am 35 years old.

These are just a few basic examples of how to use string formatters in Python 3. The possibilities are endless, and you can customize the format to fit your specific needs using the wide range of options provided by the .format() function.

Tags:

related content