我为用户名创建了这段代码,它是使用循环读取的。你知道吗
users = {
'aeinstein': {
'first':'albert',
'last':'einstein',
'location':'princeton'
},
'mcurie': {
'first':'marie',
'last':'curie',
'location':'paris',
}
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'], user_info['last']
location = user_info['location']
print("\tFull name:" + full_name.title())
print("\tLocation:" + location.title())
现在,如果观察for循环中的下面一行
full_name = user_info['first'], user_info['last']
我希望1这会附加值albert einstein
和marie curie
,但这会产生错误
print("\tFull name:" + full_name.title())
AttributeError: 'tuple' object has no attribute 'title'
但是为什么我的方法是错误的,而下面的方法是正确的。。。你知道吗
full_name = user_info['first'] + " " + user_info['last']
产生以下结果
Username: aeinstein
Full name:Albert Einstein
Location:Princeton
Username: mcurie
Full name:Marie Curie
Location:Paris
1从注释:所以当你说print("hello", "world")
这种类型的字符串连接是正确的,但在我展示的示例中不是这样的?你知道吗
表达式
user_info['first'], user_info['last']
创建一个包含两个元素的元组(在本例中,元素是字符串)。Tuple对象没有title
方法,但是如果您像user_info['first'] + " " + user_info['last']
那样使用加号操作符连接,那么您将创建一个字符串而不是Tuple,这样就可以使用title方法你的期望是错误的。你知道吗
因为
+
是字符串的连接运算符,,
不是。你知道吗通过在
user_info['first'], user_info['last']
中添加,
操作符,可以告诉Python您给它一个由两个字符串组成的元组。通过使用+
操作符,您只需将两个字符串连接成一个字符串。你知道吗相关问题 更多 >
编程相关推荐