How to Center Text in Python
To center text in Python, you can use the str.center() function or the format() function.
The following examples show how to center text in Python.
Using str.center() Function
We can use the str.center() function to center text.
Suppose we have the following string:
# Create a string
text = "Hello, world!"
# Print original string
print("Original string:", text)
# Center the string
centered_text = text.center(20)
# Print the result
print("Updated string:", centered_text)
Output: 👇️
Original string: Hello, world!
Updated string: Hello, world!
In this example, we use the str.center() function to center the string text within a width of 20 characters.
Using format() Function
We can use the format() function to center text.
Suppose we have the following string:
# Create a string
text = "Hello, world!"
# Print original string
print("Original string:", text)
# Center the string
centered_text = "{:^20}".format(text)
# Print the result
print("Updated string:", centered_text)
Output: 👇️
Original string: Hello, world!
Updated string: Hello, world!
In this example, we use the format() function to center the string text within a width of 20 characters.