0

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!

1
  • Both the examples work correctly. You should explain why you think that the second one does not work and what is the result you are expecting. Commented Jul 25, 2022 at 12:28

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.