Home > Blockchain >  Adding whitespaces to Python 3 format string using number of digits of integer
Adding whitespaces to Python 3 format string using number of digits of integer

Time:07-25

Following the Question: How to set the spaces in a string format in Python 3

Why does the first one work but the second one not?

string='Hello World!'
length = 20
print('{1:>{0}}'.format(length, string))

Results in: Hello World!

string='Hello World!'
length = len(string)
print('{1:>{0}}'.format(length, string))

Results in: Hello World!

CodePudding user response:

Both of your snippets should work fine. The reason why you receive different outputs is that length in your first example is 20, in your second example it is 12 though. As your length is always exactly as long as your string, you will never see additional whitespaces.

CodePudding user response:

In your print statement, the length variable is the total length of the output string. It includes spaces as well as the string. In the first case, 20 is the total length (8 whitespaces 12 chars). In the second case, total length is equal to the length of the string. So, it is working in both the cases.

  • Related