gpt4 book ai didi

python - 关于python中字符串格式化的几个问题。结盟

转载 作者:行者123 更新时间:2023-12-04 10:16:46 25 4
gpt4 key购买 nike

第一个问题

例如,如果我想打印很多相同宽度的线条,我可以使用

print(f'{"INFO":=^50}')
print(f'{"some info":<50}')
print(f'{"another info":>50}')

会得到

=======================INFO=======================
some info
another info

但是,如果我想得到这样的东西怎么办?

=======================INFO=======================
some info.............................another info

好的。我能行

print(f'{"INFO":=^50}')
print('some info' + f'{"another info":.>{50-len("some info")}}')

也许 python 有另一种最简单的方法?

第二个问题

对于对齐,我们可以使用 >、<、^ 和 =And = 仅适用于数字。它的工作原理与 >

例如

print(f'{13:.=5}')
print(f'{13:.>5}')
...13
...13

那么,如果它的工作原理相同,为什么我们需要 =?确定该值是一个数字?它提供更多的好处是什么?

最佳答案

对于你的第二个问题,答案在Format Specification Mini-Language中。 :

'='

Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.

当你有一个签名号码时,这就变得很清楚了:

print(f'{-13:0=5}')
# -0013

print(f'{-13:0>5}')
# 00-13

关于python - 关于python中字符串格式化的几个问题。结盟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61030633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com