In this tutorial, we are going to learn about the string method center().
The method center() accepts two arguments. First one is mandatory i.e., length and the one is optional char. It returns a new string that is centred based on the given length with a specific character.
It will take space as default character if we don't provide one. Let's see the example below.
Example
# initializing a string string = "tutorialspoint" # center -> 25 print(string.center(25))
Output
If you run the above code, then you will get the following result.
tutorialspoint
The total length of the result is 25. The method center() tries to adjust the string to the centre. Let's see the example by providing a char as the second argument.
Example
# initializing a string string = "tutorialspoint" # center -> 25 print(string.center(25, '*'))
Output
If you execute the above program, then you will get the following result.
******tutorialspoint*****
Now, we got stars in-place of the spaces. We can provide any character in place of the *. We'll get an error if we try to give a string instead of a char. Let's see the example.
Example
# initializing a string string = "tutorialspoint" # center -> 25 print(string.center(25, '***'))
Output
If you run the above code, then you will get the following result.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-12-688edb4ce9d7> in <module> 3 4 # center -> 25 ----> 5 print(string.center(25, '***')) TypeError: The fill character must be exactly one character long
We got an error saying that the fill character must be exactly one character long. Remember it while using the center() method.
Conclusion
If you have any doubts regarding the tutorial, mention them in the comment section.