python 3字符串格式(对齐) [英] python 3 string formatting (alignment)

查看:195
本文介绍了python 3字符串格式(对齐)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输出应该像这样的代码:

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

    hello   3454
    nice     222
    bye    45433
    well    3424

对齐和正确的理由给我带来了问题. 我在我的字符串{0:> 7}中尝试了此方法,但是只有具有特定位数的数字才可以.其他具有或多或少数字的数字会变得混乱.很明显,为什么他们搞砸了,但我很难找到解决方案.我讨厌只在这样一个小问题上使用常量和if语句.有什么想法吗?

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?

推荐答案

您可以尝试:

"{:>10d}".format(n),其中n是左上角数字的整数,并且

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

"{:>10s}".format(s),其中s是左移字符串的字符串

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

选择10是任意的.我建议先确定最大长度.

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:

字符串格式

您可以尝试以下操作:

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

这将使您的字符串以10个空格右移,而数字以10个空格左移,得到理想的结果 示例:

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)

这篇关于python 3字符串格式(对齐)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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