Python 字符串 ljust() 方法



Python 字符串 ljust() 方法用于将字符串左对齐,并指定宽度。如果指定的宽度大于字符串的长度,则字符串的剩余部分将填充 fillchar

默认的 fillchar 是空格。如果宽度小于或等于给定字符串长度,则返回原始字符串。

注意:只能使用一个特定字符来填充字符串的剩余部分,作为 fillchar。

语法

以下是 Python 字符串 ljust() 方法的语法

str.ljust(width[, fillchar])

参数

  • width − 这是填充后字符串的总长度。

  • fillchar − 这是填充字符;默认为空格(可选)。

返回值

此方法返回一个左对齐的字符串,其中填充字符作为参数指定,用于替换空格。如果宽度小于字符串长度,则返回原始字符串。

示例

在以下示例中,创建的字符串 "this is string example....wow!!!" 左对齐。然后,右侧的剩余空格使用指定的字符 "0" 作为 fillchar 参数,使用 Python 字符串 ljust() 方法填充。然后检索结果

# Initializing the string
str = "this is string example....wow!!!";
print (str.ljust(50, '0'))

运行以上程序时,会产生以下结果

this is string example....wow!!!000000000000000000

示例

以下是一个示例,其中生成一个长度为 89 的新字符串,并将创建的字符串 ‘Programming’ 左对齐。由于未提供 fillchar,因此使用默认的空格值。因此,检索到 ‘Programming’ 及其右侧的 78 个空格。

text = 'Programming'
# left-aligning the string
x = text.ljust(89)
print('The string after aligning is:', x)

执行以上代码时,会获得以下输出

The string after aligning is: Programming                                                                              

示例

在下面给出的示例中,我们使用 3 个键值对创建一个字典。然后我们尝试打印用 ":" 分隔的值对,我们使用 ljust() 方法来做到这一点。

# providing the dictionary
dictionary = {'Name':'Sachin', 'Sports':'Cricket', 'Age':49}
# iterating on each item of the dictionary
for keys, value in dictionary.items():
   print(str(keys).ljust(6, ' '),":", str(value))

以上代码的输出如下

Name   : Sachin
Sports : Cricket
Age    : 49     

示例

以下是一个示例,用于说明如果将多个字符作为 fillchar 参数传递,则会抛出错误,因为 fillchar 参数应只包含一个字符

text = 'Coding'
# providingh more than one fillchar character
x = text.ljust(67, '*#')
print('The new string is:', x) 

以下是以上代码的输出

Traceback (most recent call last):
   File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in 
      x = text.ljust(67, '*#')
TypeError: The fill character must be exactly one character long
python_strings.htm
广告

© . All rights reserved.