addition of int and str
hello i am reading this python book and one of the exercises says:
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.
ok so i have the following code that prints 70 spaces and the string 'allen'
def right_justify(s):
print s
right_justify(' ' * 70 + 'Allen')
but when i try to subtract the number of spaces from the string 'Allen'
sub = len('allen')
def right_justify(s):
print s
right_justify(' ' * 70 - sub + 'Allen')
i get:
"unsupported operand type(s) for -: 'str' and 'int'"
why 开发者_如何转开发does it work without the sub variable and it doesn't with it? I have checked the type of the sub and it comes out as an int.
You need parentheses:
' ' * (70 - sub) + 'Allen'
Your code is evaluated as:
((' ' * 70) - sub) + 'Allen'
That doesn't work because you can't subtract an int from a string.
As Mark says, you need parentheses around your subtraction.
Also you are doing the work of right_justify in the argument you pass. The function simply prints what you give it at the moment.
You should just pass a string, s, and let right_justify do the work on the string (i.e. work out its length then add the appropriate number of white space prior to it) before printing it.
Something like:
def right_justify(s):
sub = len(s)
new_s = ' ' * (70 - sub) + s
print new_s
right_justify('Allen')
def right_justify(s): . print (' '*(70-len(s))+s) . right_justify('allen') allen
http://en.wikibooks.org/wiki/Think_Python/Answers#Exercise_3.3
精彩评论