⊕
⊖
Contents
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='')
Run Code CopyOutput
' 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, '-'.
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.
Output
'Hello World'
Summary
In summary, to center a given string in specified resulting length, use String.center() function.
Next Topic ⫸ Python String - Remove character at specific index
⫷ Previous Topic Python - Reverse string