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 ?
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
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.
%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
%5swill pad - it won't truncate...'%.5s'but it's often clearer to just truncate the input...bar[:5]for instance...%5swill 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'%50s' % 'bob'... If what you're formatting is longer - then nothing happens.str.ljustandstr.rjustwhich are more explicit than%-5sor%5setc... So'bob'.rjust(50)rather than'%50s' % 'bob'...