What is a string.center in Python?
The center method returns a new string of a passed length. In the returned string, the source string is centered and the fill character is padded at the start and end of the string.
Syntax
string.center(width[, fillchar])
Parameters
-
width: the resulting string length. -
fillchar: the fill character to be added at the start and end of the string. It is an optional value. By default, space will be added.
Return value
-
If the
widthis greater than the length of the string, then the specified fill character will be added at the start and end of the string to make the string length equal to the passedwidthvalue. -
If the
widthis lesser than the length of the string, then the original string is returned.
The padding will be done by adding one fill character in the end and adding one to the start. This continues until the length of string meets the passed width.
Code
string = "123"print(string.center(4, '$'))print(string.center(5, '*'))print(string.center(6, '#'))print(string.center(1, '#'))
In the code above, we created a 123 string and:
-
Called the
centermethod withwidthof4andfillchar$. In this case, the string length is 3 and the width is4. 4 is greater than 3 and 4 - 3 = 1, so one$is added to the end of the string and123$is returned. -
Called the
centermethod withwidthof5andfillchar*. In this case, the string length is 3 and the width is5. 5 is greater than 3, and 5 - 3 = 2, so one*is added to the end of the string, then one*is added to the beginning of the string, and*123*is returned. -
Called the
centermethod withwidthof6andfillchar#. In this case, the string length is 3 and the width is6. 6 is greater than 3 and 6 - 3 = 3, so one#is added to the end and one#is added to the start. One#is again added to the end, and then the string and#123##are returned. -
Called
centermethod withwidthof1andfillchar#. In this case, the string length is 3 and the width is1. 1 is smaller than 3, so the string and123will be returned.