为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3146593 2023-06-20 15:57:46
所以我几乎把这段代码写对了,因为它只是关于字典的。我遇到的唯一问题是错误是一元 + 的错误操作数类型:'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'
查看完整描述

2 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

  • 用 f-string 打印

  • f-Strings:一种在 Python 中格式化字符串的新改进方法

  • PEP 498 - 文字字符串插值

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

# with

print(f'{x} runs through {y}.'

# or with

print(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:

TPLEX

SLEX

Cavitex

MCX

Star Tollway


The following Provinces are included in this data set:

Pangasinan

Subic

Bacoor,Cavite

Muntinlupa

Laguna


查看完整回答
反对 回复 2023-06-20
?
智慧大石

TA贡献1946条经验 获得超3个赞

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)

您应该删除 +y+ 旁边的逗号。


查看完整回答
反对 回复 2023-06-20
  • 2 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信