You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python扑克牌生成代码:数字转字符串失败引发TypeError报错求解

问题分析与解决

你的错误出在else分支的处理上:

  • 你写了str(card),但这个操作只是把整数card转换成了字符串,却没有将转换后的结果保存下来,card本身还是整数类型。
  • 当执行deck.append(card + suit)时,你试图把整数card和字符串suit用+拼接,Python不支持不同类型的这种操作,所以抛出了TypeError。

修正方法

直接在拼接的时候把card转为字符串即可:

修正后的代码

suits = ["♥", "♦", "♣", "♠"]
deck = []

for suit in suits:
    for card in range(1,14):
        if card == 1:
            deck.append("A" + suit)
        elif card == 11:
            deck.append("J" + suit)
        elif card == 12:
            deck.append("Q" + suit)
        elif card == 13:
            deck.append("K" + suit)
        else:
            deck.append(str(card) + suit)
print(deck)

验证结果

运行修正后的代码,就能得到你预期的输出:
['A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♦', '2♦', ...]

内容的提问来源于stack exchange,提问作者anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:32:51