如何将整数变量居中放置在字符串中?
How can I center an integer variable in a string?
这就是我想要做的:
Time Distance
---------- ----------
1 100
2 200
我试过:
count = 1
print(' Hour ' + '\t' + ' Distance ')
print('----------' + '\t' + '----------')
while count <= timeTraveled:
print(str.center(10[str(count)]) + '\t' + str.center(10[str((speedOfVehicle * count))]))
count = count + 1
无论我如何尝试将我的变量设为字符串以进行格式化,我总是遇到:
TypeError: 'int' object is not subscriptable
我想我明白了你的问题:你把 documentation 的元语法误认为是 Python 语法。
当文档描述带有可选字段的命令时,括号表示选项部分。这种描述风格至少有 45 年历史,可以追溯到 IBM 在西半球推动万物计算机的时代。有关编写命令的帮助,请参阅下面的示例。
在你的情况下,你需要像
这样的东西
print(str(count).center(10))
这是字符串class的方法;它对您调用它的字符串进行操作。在您的例子中,该字符串是 str(count)
。你能从那里跟随其他人吗?
这就是我想要做的:
Time Distance
---------- ----------
1 100
2 200
我试过:
count = 1
print(' Hour ' + '\t' + ' Distance ')
print('----------' + '\t' + '----------')
while count <= timeTraveled:
print(str.center(10[str(count)]) + '\t' + str.center(10[str((speedOfVehicle * count))]))
count = count + 1
无论我如何尝试将我的变量设为字符串以进行格式化,我总是遇到:
TypeError: 'int' object is not subscriptable
我想我明白了你的问题:你把 documentation 的元语法误认为是 Python 语法。
当文档描述带有可选字段的命令时,括号表示选项部分。这种描述风格至少有 45 年历史,可以追溯到 IBM 在西半球推动万物计算机的时代。有关编写命令的帮助,请参阅下面的示例。
在你的情况下,你需要像
这样的东西print(str(count).center(10))
这是字符串class的方法;它对您调用它的字符串进行操作。在您的例子中,该字符串是 str(count)
。你能从那里跟随其他人吗?