Python f 字符串未格式化对象的空格 属性
Python f-string not formatting whitespace for object property
我有一个名为 key
的 属性 对象并使用 f-string
我想将其格式化为在字符串左侧有 8
个空格。
这是一个例子:
object = {}
object['key'] = 'JIRA-123'
print(f"{object['key']:>8} should be 8 spaces to the right.")
print(f"{'But':>8} 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.
当我期望的输出是:
JIRA-123 should be 8 spaces to the right.
But it isn't 8 spaces to the right.
你可以试试here。
正如@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
我有一个名为 key
的 属性 对象并使用 f-string
我想将其格式化为在字符串左侧有 8
个空格。
这是一个例子:
object = {}
object['key'] = 'JIRA-123'
print(f"{object['key']:>8} should be 8 spaces to the right.")
print(f"{'But':>8} 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.
当我期望的输出是:
JIRA-123 should be 8 spaces to the right.
But it isn't 8 spaces to the right.
你可以试试here。
正如@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