Python 的 str.ljust(~) 方法返回具有指定长度的左对齐(对齐)字符串。
参数
1. width | number
返回字符串的长度。
2. fillchar | character | optional
用于填充的字符。默认为" "(空格)。
返回值
左对齐字符串填充到指定的 width 。
如果指定的width小于原始字符串的长度,则返回原始字符串。
例子
基本用法
要为 "Dog" 返回长度为 6 的左对齐字符串:
x = "Dog"
x.ljust(6)
'Dog '
请注意,Dog 后面有 3 个空格字符,以使返回的字符串为 6 字符。
填充字符参数
要使用 '*' 作为填充字符,为 "Dog" 返回长度为 6 的左对齐字符串:
y = "Dog"
y.ljust(6, '*')
'Dog***'
现在'Dog'后面有3个'*'字符,使返回的字符串成为6字符。
宽度小于原始字符串的长度
要使用 '*' 作为填充字符,为 "Dog" 返回长度为 2 的左对齐字符串:
z = "Dog"
z.ljust(2, '*')
'Dog'
由于 2 提供的宽度小于 "Dog" 的长度,因此返回原始字符串的副本。
相关用法
- Python String ljust()用法及代码示例
- Python String lower方法用法及代码示例
- Python String lstrip方法用法及代码示例
- Python String lstrip()用法及代码示例
- Python String lower()用法及代码示例
- Python String count方法用法及代码示例
- Python String isnumeric方法用法及代码示例
- Python String Center()用法及代码示例
- Python String zfill方法用法及代码示例
- Python String rstrip方法用法及代码示例
- Python String decode()用法及代码示例
- Python String count()用法及代码示例
- Python String join()用法及代码示例
- Python String casefold()用法及代码示例
- Python String isalnum()用法及代码示例
- Python String endswith方法用法及代码示例
- Python String rsplit()用法及代码示例
- Python String isidentifier()用法及代码示例
- Python String startswith()用法及代码示例
- Python String rjust方法用法及代码示例
- Python String rpartition()用法及代码示例
- Python String rpartition方法用法及代码示例
- Python String splitlines()用法及代码示例
- Python String upper()用法及代码示例
- Python String isprintable()用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Python String | ljust method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
