Python String ljust() 方法

Python String ljust() 方法

ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

Python String ljust() 语法

ljust()方法语法:

str.ljust(width[, fillchar])

Python String ljust() 参数

  • width -- 指定字符串长度。
  • fillchar -- 填充字符,默认为空格。

Python String ljust() 返回值

返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

Python String ljust() 示例1

以下实例展示了ljust()的使用方法:

#!/usr/bin/python3

str1 = "Apidemos example....wow!"

print (str1.ljust(50, '*'))

输出:

Python String ljust() 方法

Python String ljust() 示例2

使用Python字符串ljust()方法打印格式化的表格。
在这里,我们使用Python String ljust()方法来使每个项目的宽度相等,最大为10个字符。我们在这里使用了10,因为所有的项目都小于10个字符,以便均匀地进行格式化。

#!/usr/bin/python3

l = [
 ['Name', 'Age', 'Code'],
 ['Api', 21, '+855-081'],
 ['Demos', 22, '+976-254'],
 ['Com', 22, '+759-255']
]

for row in l:
 for item in row:
  # print each item after space adjustment using ljust
  print(str(item).ljust(10, ' '), end="")
 # add new line after each row printing
 print()

输出:

Python String ljust() 方法

赞(0)
未经允许不得转载:极客笔记 » Python String ljust() 方法

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
Python OS模块
Python os.chown方法Python os.write() 方法Python os.pardir 方法
Python String模块
Python String capitalize()方法Python String count()方法Python String center()方法Python String expandtabs()方法Python String index()方法Python String isalnum()方法Python String endswith()方法Python String encode()方法Python String find() 方法Python String decode()方法Python String isalpha() 方法Python String isdigit() 方法Python String islower() 方法Python String isnumeric() 方法Python String isspace() 方法Python String istitle() 方法Python String isupper() 方法Python String join() 方法Python String len() 方法Python String ljust() 方法Python String lower() 方法Python String lstrip() 方法Python String maketrans() 方法Python String max() 方法Python String min() 方法Python String replace() 方法Python String rfind() 方法Python String rindex() 方法Python String rjust() 方法Python String rstrip() 方法Python String isdecimal() 方法Python String splitlines() 方法Python String split() 方法Python String startswith() 方法Python String swapcase() 方法Python String strip() 方法Python String translate() 方法Python String title() 方法Python String zfill() 方法Python String upper() 方法
Python Math 模块
Python Math exp() 函数Python Math ceil() 函数Python Math floor() 函数Python Math fabs() 函数Python Math log10() 函数Python Math log() 函数Python Math pow() 函数Python Math modf() 函数Python round() 函数Python Math sqrt() 函数Python Math acos() 函数Python Math asin() 函数Python Math atan() 函数Python Math atan2() 函数Python Math cos() 函数Python Math degrees() 函数Python Math hypot() 函数Python Math radians() 函数Python Math sin() 函数Python Math tan() 函数
Python Random 模块
Python random choice() 函数Python random random() 函数Python random randrange() 函数Python random seed() 函数Python random shuffle() 函数Python random uniform() 函数
Python List 模块
Python List min() 方法Python List len() 方法Python List list() 方法Python List max() 方法