关于python格式对齐的问题,python 3字符串格式(对齐)

i have a code where the out put should be like this:

hello 3454

nice 222

bye 45433

well 3424

the alignment and right justification is giving me problems.

i tried this in my string {0:>7} but then only the numbers with the specific amount of digits are alright. the other numbers that have some digits more or less become messed up. it is very obvious to understand why they are messing up, but i am having trouble finding a solution. i would hate to use constant and if statements all over the place only for such a minor issue. any ideas?

解决方案

You could try:

"{:>10d}".format(n) where n is an int to pad-left numbers and

"{:>10s}".format(s), where s is a string to pad-left strings

Edit: choosing 10 is arbitrary.. I would suggest first determining the max length.

But I'm not sure this is what you want..

Anyways, this link contains some info on string formatting:

You can try this:

def align(word, number):

return "{:<10s}{:>10d}".format(word, number)

This will pad-right your string with 10 spaces and pad-left your number with 10 spaces, giving the desired result

Example:

align('Hello', 3454)

align('nice', 222)

align('bye', 45433)

align('well', 3424)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值