Python String ljust() 方法
Python String ljust() 方法根据指定的宽度左对齐字符串,如果未传递 'fillchr' 参数,则用空格填充行的剩余空间。
Syntax:
ljust(len, fillchr)
Parameters:
- len: The width of string to expand it.
- fillchr (optional): The character to fill in the remaining space.
Return Value:
Returns a new string of given length after substituting a given character in right side of original string.
示例 1
Python3
# example string
string = 'gfg'
width = 5
# print left justified string
print(string.ljust(width))
Python3
# 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, '-'))
输出:
gfg
解释:
此处,定义的最小宽度为 5。因此,结果字符串的最小长度为 5。并且,字符串'gfg' 向左对齐,这使得在单词的右侧留下两个空格。
示例 2
蟒蛇3
# 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--------------------