我正在尝试使用字符串中列表中的项目数。我的代码如下:
locations = ['usa', 'canada', 'israel', 'china']
print("I would like to visit " + len(locations) + " locations this year.")
我想把它打印出来#34;我想今年访问4个地点。"
我做错了什么?如何让len函数在这种情况下工作?
我刚刚开始学习编码,所以感谢您回答初学者问题!
答案 0 :(得分:1)
len()
函数返回数字类型,而带字符串的串联(+)需要另一个字符串。因此,您需要先使用str()
函数将数字转换为字符串:
locations = ['usa', 'canada', 'israel', 'china']
print("I would like to visit " + str(len(locations)) + " locations this year.")
答案 1 :(得分:0)
您可以尝试使用string.format()方法。
示例:
A=[a,b,c,d]
S=“I was away for {}days”.format(len(A))
这应该给你
“我离开了4天” 更多信息可以在这里找到 https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3