Reputation: 99
Python provides a built-in function called len
that returns the length of a string, so the value of len('allen')
is 5. Write a function named right_justify
that takes a string named s
as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
Author's solution:
def right_justify(s):
print (' '*(70-len(s))+s)
>>> right_justify('allen')
My solution:
def right_justify(s):
space_count=70-len(s)
for i in range(0,space_count,1):
print " ",
print s
strng=raw_input("Enter your desired string:")
print len(strng)
right_justify(strng)
The output of my code is different than the output of author's code: I am getting twice as many spaces, e.g. 130 instead of 65.
But it seems to me that the two pieces of code are logically equivalent. What am I overlooking?
Upvotes: 0
Views: 192
Reputation: 1
I would prefer the function str.rjust(70," ") which does the trick, I think, like so: strng.rjust(70," ")
Upvotes: 0
Reputation: 12939
Your code has 130 spaces, the author's code has 65 spaces. This is because
print " ",
...adds a space. What you want is:
print "",
Upvotes: 0
Reputation: 32497
The problem is with your print statement
print " ",
will print two spaces for each iteration of the loop. When terminating the print statement with a comma, subsequent calls will be delimited by a space.
On a side note, another way to define your right_justify
function would be
def right_justify(s):
print '%70s' % s
Upvotes: 2
Reputation: 1105
The print " ",
line actually prints two spaces (one from the " "
, one from the ,
). You could replace it with print "",
to have your function work identically to the original.
Upvotes: 0