Python f字符串未格式化对象属性的空白

Python f字符串未格式化对象属性的空白,python,string-formatting,Python,String Formatting,我有一个对象,其属性名为key,使用f-string我想将其格式化为字符串左侧有8空格 以下是一个例子: object={} 对象['key']='JIRA-123' 打印(f“{object['key']:>8}应该是右边的8个空格。”) 打印(f“{'But':>8}右边不是8个空格。”) 运行时,这是输出: JIRA-123 should be 8 spaces to the right. But it isn't 8 spaces to the right. 当我期望的输出

我有一个对象,其属性名为
key
,使用
f-string
我想将其格式化为字符串左侧有
8
空格

以下是一个例子:

object={}
对象['key']='JIRA-123'
打印(f“{object['key']:>8}应该是右边的8个空格。”)
打印(f“{'But':>8}右边不是8个空格。”)
运行时,这是输出:

JIRA-123 should be 8 spaces to the right.
     But it isn't 8 spaces to the right.
当我期望的输出是:

     JIRA-123 should be 8 spaces to the right.
     But it isn't 8 spaces to the right.

您可以试试。

正如@Stephen Rauch在评论中提到的,您对格式感到困惑。 以下是解释,希望对您有所帮助

>>> len('But')
>>> 3
>>> f"{'But':>8}" # output will be 8 characters wide 
>>> '     But'    # Since len of But is 3 left 5 length will be filled out by whitespaces in left
>>> object['key'] = 'JIRA-123'
>>> len(object['key'])
>>> 8
>>> f"{object['key']:>8}" # output will be 8 characters wide 
>>> 'JIRA-123'            # since length is already of 8 no whitespaces in left

您对格式感到困惑。您需要的只是空格,而不是字段宽度。
:>8
意味着它将位于8个字符宽的字段中。如果该值小于该值,将在左侧添加空格。使用“对齐”时,您会说“在n个字符的空间中,我希望我的k个字符字符串向左/中间/向右对齐”。如果n和k相等,则得到一个“左”对齐的字符串。尝试在f字符串(未对齐)之前添加“*8”,它将起作用