不能连接' str'和' int'对象“错误

时间:2015-02-15 22:22:41

标签: python concatenation

我一直收到这个错误,我知道它与“option =”行有关,我不知道我做错了什么。

deck = Deck()
deck.shuffle()
pCard1 = deck.deal()
pCard2 = deck.deal()
print "'s cards are :", pCard1, "and", pCard2
dCard1 = deck.deal()
dCard2 = deck.deal()
print "The Dealer's cards are:", dCard1, "and", dCard2
playerTotal = (Card.getCardValue(pCard1) + Card.getCardValue(pCard2))
dealerTotal = (Card.getCardValue(dCard1) + Card.getCardValue(dCard2))
if playerTotal == 21:
    rules(playerTotal,dealerTotal)
if dealerTotal == 21:
    rules(playerTotal,dealerTotal)
option = raw_input("Your total is" + playerTotal + ", Would you like to take a hit or stay?")
if option == "stay" or option == "Stay":
    dealersTurn(dealerTotal)
    rules(playerTotal,dealerTotal)

2 个答案:

答案 0 :(得分:2)

只需使用str()转换为字符串

option = raw_input("Your total is" + str(playerTotal) + ", Would you like to take a hit or stay?")

答案 1 :(得分:2)

您需要使用str将整数转换为字符串,Python不会为您执行此操作。

option = raw_input("Your total is" + str(playerTotal) + ", Would you like to take a hit or stay?")

或者,您可以使用the string formatting operator(奇怪的是,%通常是模数运算符)而不是连接。

option = raw_input("Your total is %d, Would you like to take a hit or stay?" % playerTotal)

你应该使用哪个?要看。格式对于长消息很有用,这些消息很难读取,中间有很多变量。当你需要按摩变量时,它们也很有用,例如证明它们或证明它们有一定数量的数字(比如将0变为0.00)。否则,请使用连接。