Python String center() Method

29-12-22 Ahmed Obaid 1167 0

​The center() function creates and returns a new string with the specified character inside it. If no specified character is provided, it returns a new string, adding, by default, blank spaces.


How to formulate it like this:


string.center(length [, fillchar])

length: is an integer value that represents the total length of the string together with the leading space characters.

fillchar: (optional) contains a character. If not provided, the blank space is used as the default argument.

Return value: The center() function returns a new string with the specified character inside. If a specific character is not provided, it defaults to adding blank spaces.


In the following example, we will print the string "Learn Python", with the middle default space, which takes up 18 characters.

Example:


string = "Learn Python"
output = string.center(18)
# here fillchar not provided so takes space by default.
print("The string after applying the center() function is: ", output)

The output will be:


The string after applying the center() function is: Learn Python

In the following example we will print the string "Learn Python", and fill in the blanksundefined side by fill letter specified as ( - ) .

 Example:


string = "Learn Python"
output = string .center(20, '-')
print("The string after applying the center() function is:", output)

 The output will be:


The string after applying the center() function is: ---Learn Python----

 We will print the string "Learn Python", and the side spaces are filled with the fill character specified as ( x ) .


string = "Learn Python"
output = string .center(20, 'x')
print("The string after applying the center() function is:", output)

 The output will be:


The string after applying the center() function is: xxxLearn Pythonxxxx

 The center() function does not modify the original string and add the specified fill character to it, if the number of side fill characters is less than the length of the original string.

 Example:


string = "Learn Python"
output = string .center(7, 'x')
print("The string after applying the center() function is:", output)

 The output will be:


The string after applying the center() function is: Learn Python

 The center() function does not accept more than one fill character, if it is a character count undefined Side fill more than one character we will get error.

 Example:


string = "Learn Python"
output = string .center(20, 'xx')
print("The string after applying the center() function is:", output)

 We will get this error:


Traceback (most recent call last):
File "./prog.py", line 2, in <module>
TypeError: The fill character must be exactly one character long

 External sources:

 Built-in functions - official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python Python String string methods python python string center method

Share page