你好,我正在读这本 Python 书,其中一个练习说:
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.
好的,所以我有以下代码打印 70 个空格和字符串 'allen'
def right_justify(s):
print s
right_justify(' ' * 70 + 'Allen')
但是当我尝试从字符串“Allen”中减去空格数时
sub = len('allen')
def right_justify(s):
print s
right_justify(' ' * 70 - sub + 'Allen')
我得到:
"unsupported operand type(s) for -: 'str' and 'int'"
为什么它在没有子变量的情况下工作,而在有子变量的情况下却不行? 我检查了 sub 的类型,结果显示为 int。
请您参考如下方法:
你需要括号:
' ' * (70 - sub) + 'Allen'
您的代码被评估为:
((' ' * 70) - sub) + 'Allen'
这行不通,因为您不能从字符串中减去 int。
