How to achieve center alignment of python strings

WBOY
Release: 2024-03-01 21:00:12
forward
1340 people have browsed it

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)
Copy after login

The output result is:

 Hello, World!
Copy after login

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)
Copy after login

The output result is:

***Hello, World!****
Copy after login

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!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template