Python string center method explanation with example
center() is an inbuilt method defined in the python string. Using this method, we can centre align a string. By default, we can centre align a string with space on its side. Or we can give specific characters as the fill character.
Syntax of center() :
Following is the syntax of center() :
Here,str is the string, length is the total length of the final string and fillchar is the character to fill both side of the string str.
fillchar is optional. If you don’t pass any character as fillchar, it will use blank space to fill on both sides of the string.
Return value of center() :
This method returns one string with the caller string str in the middle and fillchar on the sides.
Python program :
Let’s try to implement center() method :
original_str = "hello world" print(original_str.center(10)) print(original_str.center(30)) print(original_str.center(30,'*'))
It will give the below output :
hello world hello world *********hello world**********
- For the first print statement, the result string doesn’t have any change because we want to center 10 characters of the string, but the size of the string is 11.
- The second string size is 30 total with equal amount of blank spaces on both side.
- The third string size is 30 total with * on both side.
Similar tutorials :
- Python raw strings : Explanation with examples
- Convert string to float in python
- Python swap case of each character of a string
- Python example program to split a string at linebreak using splitlines
- Python program to calculate total vowels in a string
- Python program to check if two strings are an anagram or not