Python打印字典中的元素

2024-09-27 00:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我为用户名创建了这段代码,它是使用循环读取的。你知道吗

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 einsteinmarie 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")这种类型的字符串连接是正确的,但在我展示的示例中不是这样的?你知道吗


Tags: nameinfotitlelocationusersfullfirstlast
3条回答

表达式user_info['first'], user_info['last']创建一个包含两个元素的元组(在本例中,元素是字符串)。Tuple对象没有title方法,但是如果您像user_info['first'] + " " + user_info['last']那样使用加号操作符连接,那么您将创建一个字符串而不是Tuple,这样就可以使用title方法

full_name = user_info['first'], user_info['last']

I expect this to append the value albert einstein and marie curie […]

你的期望是错误的。你知道吗

but why is my method wrong and the following therefore correct...

full_name = user_info['first'] + " " + user_info['last']

因为+是字符串的连接运算符,,不是。你知道吗

通过在user_info['first'], user_info['last']中添加,操作符,可以告诉Python您给它一个由两个字符串组成的元组。通过使用+操作符,您只需将两个字符串连接成一个字符串。你知道吗

相关问题 更多 >

    热门问题