2

Following is my code snippet.

bar = "Hello World"
print("%5s" % bar)

I am trying to print Hello from bar. But %5s is not working as it should.

What am I doing wrong ?

9
  • 1
    No - it's working as it should... %5s will pad - it won't truncate... Commented Sep 16, 2017 at 10:14
  • 1
    You can (ab)use '%.5s' but it's often clearer to just truncate the input... bar[:5] for instance... Commented Sep 16, 2017 at 10:15
  • 1
    %5s will make sure it's at least 5 characters (padding with a fill character (space by default) if needs be)... if it's more - then nothing happens Commented Sep 16, 2017 at 10:16
  • 1
    As I said - it makes the width at least that amount... try '%50s' % 'bob'... If what you're formatting is longer - then nothing happens. Commented Sep 16, 2017 at 10:19
  • 1
    If you're not doing something more complicated in the formatting, then there's also str.ljust and str.rjust which are more explicit than %-5s or %5s etc... So 'bob'.rjust(50) rather than '%50s' % 'bob'... Commented Sep 16, 2017 at 10:26

3 Answers 3

2

It is simpler to do this:

bar = "Hello World"

print (bar[:5])

using '%5s' will simply return the whole string because the string is >5 characters long, if you use '%20's for example you will get white space followed by the whole string, like so.

bar = "Hello World"
print("%20s" % bar)
>>>         Hello World
Sign up to request clarification or add additional context in comments.

3 Comments

I am aware of slicing. I was trying to understand what that format does.
I believe that '%5s' will return the string 'Hello World' without any padding, this is because 'Hello World' is 11 characters long, if you change the number from '%5s' to say '%20s' the string will be padded with 9 spaces before 'Hello World' is displayed. Simply put, it adds white space before a string.
Yep. Your belief is true. My answer is based on same.
0

In following code:

bar = "Hello World"
print("%5s" % bar)

Total width of bar should be more than 5 characters otherwise padding spaces will be added as prefix.

Here padding is 5 but string length is 11. So nothing will happen.

In following code:

bar = "Hello World"
print("%15s" % bar)

Padding is 15 which exceeds string length 11. Hence 4 spaces will be added in beginning.

Output will be: ----Hello World

- denotes one space.

Comments

0

%5s will pad the string with spaces if it is shorter than 5 characters e.g.

>>> print("%5s" % "Hi")
   Hi

To truncate the string you can either use %.5s

>>> bar = "Hello World"
>>> print("%.5s" % bar)
Hello

or can slice the string as follows

>>> bar = "Hello World"
>>> print("%s" % bar[:5])
Hello

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.