gpt4 book ai didi

python - 添加 int 和 str

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:21 25 4
gpt4 key购买 nike

你好,我正在读这本 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。

关于python - 添加 int 和 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7648882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com