不同长度的Python填充字符串 [英] Python padding strings of different length

查看:287
本文介绍了不同长度的Python填充字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个我知道可以用字符串格式解决的问题,但是我真的不知道从哪里开始. 我想做的是创建一个填充列表,以便在逗号前有n个字符,如下表所示.

So I have a problem I know can be solved with string formatting but I really don't know where to start. What I want to do is create a list that is padded so that there is n number of characters before a comma as in the list below.

 1148,
   39,
  365,
    6,
56524,

干杯,谢谢您的帮助:)

Cheers and thanks for your help :)

推荐答案

最直接的方法是使用

The most straight-forward way is to use the str.rjust() function. For example:

your_list = [1148, 39, 365, 6, 56524]

for element in your_list:
    print(str(element).rjust(5))

您会得到:

 1148
   39
  365
    6
56524

还有 str.center() str.ljust() 用于其他方向的字符串对齐.

There are also str.center() and str.ljust() for string justification in other directions.

但是您也可以通过格式化来实现:

But you can also do it via formatting:

your_list = [1148, 39, 365, 6, 56524]

for element in your_list:
    print("{:>5}".format(element))

这篇关于不同长度的Python填充字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆