How to Center a String in Specific Length in Python?
Python - Center a String in Specific Length
To center a string in specific length, call center() function on this string, and pass the length of the resulting string.
String.center(length)
Examples
1. Center given string in a length of 20
In this example, we will take a string 'Hello World' and center this string with a resulting length of 20.
Python Program
x = 'Hello World'
result = x.center(20)
print("'", result, "'", sep='')
Output
' Hello World '
2. Center a given string in a length of 20 and fill the with '-'
In this example, we will take a string 'Hello World' and center this string with a resulting length of 20, but fill the extra length with specific character, say, '-'
.
Python Program
x = 'Hello World'
result = x.center(20, '-')
print(result)
Output
----Hello World-----
3. Center a given string, but string length is greater
In this example, we will take a string 'Hello World' and center this string with a resulting length of 5. Since the given length is less than the original string length, the string is returned as is.
Python Program
x = 'Hello World'
result = x.center(5)
print("'", result, "'", sep='')
Output
'Hello World'
Summary
In summary, to center a given string in specified resulting length, use String.center() function.