Python中字符串对齐

有时候字符串需要做一些左,中,右对齐操作,比如商场打印的发票的,收费项都是左对齐,金额右对齐,抬头中央对齐,在Python的有对应的三个函数ljust(), center(), rjust() 分别对应左、中、右操作! 有两个用法:

  • 一种是默认不带参数,则默认是以空格填充
>>> print("|" + "OK".ljust(10) + "|"  + "OK".rjust(10) + "|" + "OK".center(10) + "|")
|OK        |        OK|    OK    |

  • 一种是带参数,则以第二个参数作为填充
>>> print("OK".center(10, '+'))
++++OK++++
>>> print("OK".ljust(10, '+'))
OK++++++++
>>> print("OK".rjust(10, '+'))
++++++++OK

猜你喜欢

转载自blog.csdn.net/jerry_1126/article/details/80671695