字符串对齐在许多日常应用程序中经常使用。Python在其语言中提供了几个有助于对齐字符串的函数。此外,还提供了一种添加用户指定的填充而不是空格的方法。
这些功能是:
str.ljust(s, width[, fillchar]) str.rjust(s, width[, fillchar]) str.center(s, width[, fillchar])
这些函数分别在给定宽度的字段中左对齐、右对齐和居中对齐字符串。它们返回一个宽度至少为个字符的字符串,该字符串是通过填充字符串创建的 s 和这个角色 菲尔查尔 (默认为空格)直到右、左或两侧的给定宽度。字符串永远不会被截断。
这个函数 中心对齐 根据指定的宽度输入字符串,如果’ 菲尔克 “争论没有通过。
语法: 中心(len,fillchr)
参数: 伦恩: 用于扩展的字符串的宽度。 fillchr(可选): 要填充剩余空间的字符。
返回值: 由此产生的中心对齐的字符串扩展了给定的宽度。
# Python3 code to demonstrate # the working of center() cstr = "I love geeksforgeeks" # Printing the original string print ( "The original string is : " , cstr, "" ) # Printing the center aligned string print ( "The center aligned string is : " ) print (cstr.center( 40 ), "" ) # 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##########
这个函数 左对齐 根据指定的宽度输入字符串,如果’ 菲尔克 “争论没有通过。
语法: ljust(len,fillchr)
参数: 伦恩: 用于扩展的字符串的宽度。 fillchr(可选): 要填充剩余空间的字符。
返回值: 扩展给定宽度的左对齐字符串。
# Python3 code to demonstrate # the working of ljust() lstr = "I love geeksforgeeks" # Printing the original string print ( "The original string is : " , lstr, "" ) # 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--------------------
这个函数 右对齐 根据指定的宽度输入字符串,如果’ 菲尔克 “争论没有通过。
语法: rjust(len,fillchr)
参数: 伦恩: 用于扩展的字符串的宽度。 fillchr(可选): 要填充剩余空间的字符。
返回值: 扩展给定宽度的右对齐字符串。
# Python3 code to demonstrate # the working of rjust() rstr = "I love geeksforgeeks" # Printing the original string print ( "The original string is : " , rstr, "" ) # 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