I am trying to make a simple text-based game in Python. The idea of which revolves around a deck of playing cards, representing the card face values with A,2,3,4,5,6,7,8,9,10,J,Q, and K (Joker is not used). The suit of the cards will be represented by s,d,h, and c. As an example, “Ace of Hearts” would be represented as Ah.
I am using two random.choice() functions to choose a random face value and a random suit, with 10 being represented by ‘X’. This is where I encounter my problem. Ideally, I would like to change ‘X’ when it appears to ’10’. Here is my “test” code for generating a random card:
import random
firstvar = random.choice('A23456789XJQK')
secondvar = random.choice('sdhc')
newvar = firstvar + secondvar
if newvar[0] == 'X':
newvar[0] = '10'
print newvar
else:
print newvar
I quickly found out that this causes an error.
TypeError: ‘str’ object does not support item assignment
In short, my question is: “How would I go about changing ‘X’ in my program to ’10’?
Thanks for any help you can offer.
Change it before you concatenate.
Alternatively, don’t use ‘X’ to begin with:
Another alternative would be the
replacemethod on strings:The second method is probably best for this situation unless you need to use ‘X’ elsewhere in your code and that can’t be changed. It is worth looking at other methods for dealing with immutable strings though because the second isn’t always appropriate.