我试着运行这段代码,它给了我这个错误,“TypeError:只能连接str(不是“NoneType”)到str”。我需要知道该怎么做。
我试着用“真实”而不是“无”
users = {'zacc_eli':{'first_name': 'Zaccheus',
'middle_name': None,
'last_name': 'Elisha',
'age': 19},
'_Djvy_': {'first_name': 'daniel',
'middle_name': 'joshua',
'last_name': 'adebayo',
'age': None}}
for username, details in users.items():
print(username + ':')
full_name = details['first_name'] + ' ' + details['middle_name'] + ' ' + details['last_name']
full_name2 = details['first_name'] + ' ' + details['last_name']
age = details['age']
if details['middle_name'] == None :
print('\tFull Name: ' + full_name2.title())
else:
print('\tFull Name: ' + full_name.title())
if details['age'] != None:
print('\tAge: ' + str(age))
我希望没有中间名时不会出现双空格,没有年龄时不会出现年龄。
这条线
full_name = details['first_name'] + ' ' + details['middle_name'] + ' ' + details['last_name']
如果details['middle_name']
是None
而不是str
值,则失败。不过,在这一点上,您还没有检查情况是否如此。直到4行之后,你才能这样做。
Python并不懒惰(像Haskell一样);它不会等到您实际使用full_name
的值来计算分配给它的表达式。
相反,在执行任何需要str
的操作之前,请检查该值:
for username, details in users.items():
print(username + ':')
first = details['first_name']
middle = details['middle_name']
last = details['last_name']
if middle is None:
full_name = first + ' ' + last
else:
full_name = first + ' ' + middle + ' ' + last
# Or a one-liner
# full_name = ' '.join([for x in [first, middle, last] if x is not None])
age = details['age']
print('\tFull Name: ' + full_name.title())
if age is not None:
print('\tAge: ' + str(age))