Python字符串 | ljust(), rjust(), 中心()
字符串对齐经常用于许多日常应用程序中。 Python在其语言中提供了几个有助于对齐字符串的函数。此外,还提供了一种添加用户指定填充而不是空格的方法。
这些功能是:
str.ljust(s, width[, fillchar])
str.rjust(s, width[, fillchar])
str.center(s, width[, fillchar])
这些函数分别在给定宽度的字段中左对齐、右对齐和居中字符串。它们返回一个至少为宽度字符宽的字符串,该字符串是通过用字符fillchar (默认为空格)填充字符串s直到右侧、左侧或两侧的给定宽度而创建的。字符串永远不会被截断。
此函数中心根据指定的宽度对齐字符串,如果未传递“ fillchr ”参数,则用空格填充行的剩余空间。
Syntax :
center( len, fillchr )
Parameters :
len : The width of string to expand it.
fillchr (optional): The character to fill in remaining space.
Return Value :
The resultant center aligned string expanding the given width.
# Python3 code to demonstrate
# the working of center()
cstr = "I love geeksforgeeks"
# Printing the original string
print ("The original string is : \n", cstr, "\n")
# Printing the center aligned string
print ("The center aligned string is : ")
print (cstr.center(40), "\n")
# Printing the center aligned
# string with fillchr
print ("Center aligned string with fillchr: ")
print (cstr.center(40, '#'))
输出 :
The original string is :
I love geeksforgeeks
The center aligned string is :
I love geeksforgeeks
Center aligned string with fillchr:
##########I love geeksforgeeks##########
此函数根据指定的宽度左对齐字符串,如果未传递“ fillchr ”参数,则用空格填充行的剩余空间。
Syntax :
ljust( len, fillchr )
Parameters :
len : The width of string to expand it.
fillchr (optional): The character to fill in remaining space.
Return Value :
The resultant left aligned string expanding the given width.
# Python3 code to demonstrate
# the working of ljust()
lstr = "I love geeksforgeeks"
# Printing the original string
print ("The original string is : \n", lstr, "\n")
# Printing the left aligned
# string with "-" padding
print ("The left aligned string is : ")
print (lstr.ljust(40, '-'))
输出 :
The original string is :
I love geeksforgeeks
The left aligned string is :
I love geeksforgeeks--------------------
此函数根据指定的宽度右对齐字符串,如果未传递“ fillchr ”参数,则用空格填充行的剩余空间。
Syntax :
rjust( len, fillchr )
Parameters :
len : The width of string to expand it.
fillchr (optional) : The character to fill in remaining space.
Return Value :
The resultant right aligned string expanding the given width.
# Python3 code to demonstrate
# the working of rjust()
rstr = "I love geeksforgeeks"
# Printing the original string
print ("The original string is : \n", rstr, "\n")
# Printing the right aligned string
# with "-" padding
print ("The right aligned string is : ")
print (rstr.rjust(40, '-'))
输出 :
The original string is :
I love geeksforgeeks
The right aligned string is :
--------------------I love geeksforgeeks