Search code examples
pythonstring-formatting

Python f-string not formatting whitespace for object property


I have an object with a property called key and using f-string I want to format it to have 8 whitespaces to the left of the string.

Here is an example:

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.")

When this is run, this is the output:

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

When the output I'm expecting is:

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

You can try it out here.


Solution

  • As mentioned in comments by @Stephen Rauch you are confused with formatting. Here is the explanation Hope you will find helpful.

    >>> 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