📜  Python()中的字符串rjust()和ljust()

📅  最后修改于: 2022-05-13 01:55:24.842000             🧑  作者: Mango

Python()中的字符串rjust()和ljust()

1. String rjust() 字符串 rjust()方法在将给定字符替换为原始字符串。

句法:

参数:

回报:

例子

# Python program to demonstrate working of 
# rjust()
string = 'geeks'
length = 8
  
# If no fill character is provided, space
# is used as fill character
print(string.rjust(length))

输出:

geeks

例子

# example string
string = 'geeks'
length = 8
fillchar = '*'
  
print(string.rjust(length, fillchar))

输出:

***geeks  

2. 字符串 ljust()
字符串ljust()方法在替换原始字符串右侧的给定字符后返回给定长度的新字符串。

句法:

参数:

回报:

示例 1

# example string
string = 'geeks'
length = 8
  
# If no fill character is provided, space
# is used as fill character.
print(string.ljust(length))

输出:(geeks后面打印三个空格)

geeks   

示例 2

# example string
string = 'geeks'
length = 8
fillchar = '*'
  
# print left justified string
print(string.ljust(length, fillchar))

输出:

geeks***