如何删除一元 +: 'str' 的错误操作数类型错误。在我的循环句子中

所以我几乎把这段代码写对了,因为它只是关于字典的。我遇到的唯一问题是错误是一元 + 的错误操作数类型:'str'。


这是我的代码:


express_file = {'TPLEX':'Pangasinan', 'SLEX':'Subic', 'Cavitex':'Bacoor,Cavite','MCX':'Muntinlupa','Star Tollway':'Laguna'}

for x,y in express_file.items():

    print(x,'runs through',+y+ '.')

print('The following Expressway are included in this data set:')

for x in express_file.keys():

    print(x)

print('\nThe following Provinces are included in this data set:')

for x in express_file.values():

    print(x)

追溯

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-782fcd7b686e> in <module>

      1 express_file = {'TPLEX':'Pangasinan', 'SLEX':'Subic', 'Cavitex':'Bacoor,Cavite','MCX':'Muntinlupa','Star Tollway':'Laguna'}

      2 for x,y in express_file.items():

----> 3     print(x,'runs through',+y+ '.')

      4 print('The following Expressway are included in this data set:')

      5 for x in express_file.keys():


TypeError: bad operand type for unary +: 'str'


慕妹3146593
浏览 122回答 2
2回答

慕仙森

用 f-string 打印f-Strings:一种在 Python 中格式化字符串的新改进方法PEP 498 - 文字字符串插值# replace print(x,'runs through',+y+ '.')# withprint(f'{x} runs through {y}.'# or withprint(x,'runs through ' +y+ '.')  # note the added space after through and the removal of the ,更新脚本express_file = {'TPLEX':'Pangasinan', 'SLEX':'Subic', 'Cavitex':'Bacoor,Cavite','MCX':'Muntinlupa','Star Tollway':'Laguna'}for x,y in express_file.items():    print(f'{x} runs through {y}.')print('The following Expressway are included in this data set:')for x in express_file.keys():    print(x)print('\nThe following Provinces are included in this data set:')for x in express_file.values():    print(x)[out]:TPLEX runs through Pangasinan.SLEX runs through Subic.Cavitex runs through Bacoor,Cavite.MCX runs through Muntinlupa.Star Tollway runs through Laguna.The following Expressway are included in this data set:TPLEXSLEXCavitexMCXStar TollwayThe following Provinces are included in this data set:PangasinanSubicBacoor,CaviteMuntinlupaLaguna

智慧大石

express_file = {'TPLEX':'Pangasinan', 'SLEX':'Subic', 'Cavitex':'Bacoor,Cavite','MCX':'Muntinlupa','Star Tollway':'Laguna'}for x,y in express_file.items():&nbsp; &nbsp; print(x,'runs through'+y+ '.')print('The following Expressway are included in this data set:')for x in express_file.keys():&nbsp; &nbsp; print(x)print('\nThe following Provinces are included in this data set:')for x in express_file.values():&nbsp; &nbsp; print(x)您应该删除 +y+ 旁边的逗号。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python