ItsMyCode |
Python String center() method is a built-in function used to align the string to the center by filling the paddings to the left and right of the string with a specified fillchar(default fill character is an ASCII space).
center() Syntax
The syntax of center()
method is:
string.center(width[, fillchar])
center() Parameter
The center()
function takes 2 parameters.
- width – length of the string with padded characters
- fillchar (optional) – Character which needs to be padded. If not provided, space is used as the default character.
center() Return Value
The center()
function returns a string padded with a specified fillchar. It doesn’t modify the original string.
The original string is returned if the width is less than or equal to len(s)
Example 1: center() Method With Default fillchar
text = "Python Rocks"
# Defaults fills with space on both sides of string
new_text = text.center(20)
print("Original String:", text)
print("Centered String:", new_text)
Output
Original String: Python Rocks
Centered String: Python Rocks
Example 2: center() Method With * fillchar
text = "Python Rocks"
# Defaults fills with * on both sides of string
new_text = text.center(20, "*")
print("Original String:", text)
print("Centered String:", new_text)
Output
Original String: Python Rocks
Centered String: ****Python Rocks****
Example 3: Returns original string if the width is less than length of string
In this example the width specified is 10 and the length of the string is 12. Hence the center()
method returns the original string as-is without any padding characters.
text = "Python Rocks"
# width is less then length of string
new_text = text.center(10, "*")
print("Length of string:", len(text))
print("Original String:", text)
print("Centered String:", new_text)
Output
Length of string: 12
Original String: Python Rocks
Centered String: Python Rocks
The post Python String center() appeared first on ItsMyCode.
from Planet Python
via read more
No comments:
Post a Comment