tags:

views:

46

answers:

2

Hello,

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.

+2  A: 

Change it before you concatenate.

firstvar = random.choice('A23456789XJQK') 
secondvar = random.choice('sdhc') 
newvar = (firstvar + secondvar) if firstvar != 'X' else ('10' + secondvar)

Alternatively, don't use 'X' to begin with:

firstvar = random.choice(['A', '2', '3', ..., '10', ...])

Another alternative would be the replace method on strings:

newvar = firstvar.replace('X', '10') + secondvar

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.

aaronasterling
I agree with #2, just make it a list and put in 10 since that's what you're changing it to right away.
It works perfectly. Thank you!
Python Newbie
@user470379 Right, that's probably best in this situation but the immutability of strings is a common enough stumbling point (I'm an alright python coder and I still trip over it sometimes) that it's worth looking at all of the options for dealing with it from a more general perspective.
aaronasterling
A: 

In python you cannot modify a string. You could deal with this by creating a new string combing the '10' and the rest of the original string

newvar = '10' + newvar[1:]

But that is really ugly. You are better of constructing the string correctly in the first place:

firstvar = random.choice(['A','2','3','4','5','6','7','8','9','10','J','Q', 'K'])
secondvar = random.choice('sdhc')
newvar = firstvar + secondvar

If you are coming from other languages you may be used to thinking about operations as modifying strings. You are better off to create your string correctly in the first place. Of course, if you are dealing with strings from user input that is different.

Winston Ewert