使用前一个美元符号格式化右对齐数字

时间:2018-05-08 18:25:09

标签: python python-3.x formatting format

我尝试创建一个简单的函数,它返回一个带有前面一个美元符号的右对齐数字。

预期产出:

$1000
  $10
 $100

我目前的代码是:

def aligned_num(num):
    print('${0:4}'.format(num))

但是这给了:

$1000
$  10
$ 100

有人能帮助我吗? 感谢。

2 个答案:

答案 0 :(得分:0)

这似乎是这样的:

def aligned_num(num):
    str_num = '$'+str(num)
    print('{0:>5}'.format(str_num))

有没有办法,不将整数更改为字符串?

答案 1 :(得分:0)

您可以在格式字符串中放入格式字符串。

l = [1000, 10, 100]

for n in l:
    # 3.6 and newer:
    print(f"Money earned: {f'${n}':>5}.")

for n in l:
    # older than 3.6:
    print("Money earned: {0:>5}.".format("${0}".format(n)))

结果:

Money earned: $1000.
Money earned:   $10.
Money earned:  $100.

Money earned: $1000.
Money earned:   $10.
Money earned:  $100.