如何将len()
值转换为字符串以成功打印字符串表达式?
vacation = ['Rick', 'Paris', 'Tom', 'James']
print("I live with " + len(vacation) + " people")
我收到错误
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
print("I live with " + len(vacation) + " people")
TypeError: must be str, not int
使用 str 函数将 int 转换为字符串:
print("I live with " + str(len(vacation)) + " people")
对于此类任务,使用格式化字符串是比将小块与+
连接在一起要方便得多
vacation = ['Rick', 'Paris', 'Tom', 'James']
print("I live with %d people" % len(vacation))
你可以
这样做:
print("I live with %s people" % len(vacation))
或
print('I live with {} people'.format(len(vacation)))
%s
和 {}
是传递的参数的占位符。
使用 str 函数。
假期 = ["里克"、"巴黎"、"汤姆"、"詹姆斯"]
print("I Live With " + str(len(vacation(( + "people"(
vacation = ['Rick', 'Paris', 'Tom', 'James']
print(f"I live with {len(vacation)} people")
https://docs.python.org/3/reference/lexical_analysis.html 了解更多信息。