Home  >  Article  >  Backend Development  >  How to achieve center alignment of python strings

How to achieve center alignment of python strings

WBOY
WBOYforward
2024-03-01 21:00:121336browse

How to achieve center alignment of python strings

pythonThe center alignment of string can be achieved using the built-in method center() of the string. The center() method accepts an integer as the width parameter, which is used to specify the total width of the string, and then centers the original string within this width and fills it with space characters.

The following is a sample code:

text = "Hello, World!"
width = 20

centered_text = text.center(width)
print(centered_text)

The output result is:

 Hello, World!

In the above example, the string text is center aligned into a string with a total width of 20. Since the length of text is 13, 3 space characters are padded on the left and right sides.

You can also specify the character used for padding by adding an optional fillchar parameter. For example, if you want to fill in the blanks with * characters, you would write:

text = "Hello, World!"
width = 20

centered_text = text.center(width, '*')
print(centered_text)

The output result is:

***Hello, World!****

In this example, the * characters are used to fill in the blanks.

The above is the detailed content of How to achieve center alignment of python strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete