0

I'm trying to make a program where the computer randomly picks a word from a list then shuffle the letters from that word around and it's not working. Why is it not working?

import random
mysports= ["swimming" , "basketball" , "soccer" , "cross country" , 
"football" , "cross-country skiing"]
letters = mysports[0]
letters1 = mysports[1]
letters2 = mysports[2]
letters3 = mysports[3]
letters4 = mysports[4]
letters5 = mysports [5]
a = (random.choice(mysports)) 
if a == mysports[0]:
   b = random.shuffle(letters)
   print (b)
elif a == mysports[1]:
   c = random.shuffle(letters1)
   print (c)
elif a == mysports[2]:
   d = random.shuffle(letters2)
   print (d)
elif a == mysports[3]:
   e = random.shuffle(letters3)
   print (e)
elif a == mysports[4]:
   f = random.shuffle(letters4)
   print (f)
elif a == mysports[5]:
   g = random.shuffle(letters5)
   print (g)

This is what it gives me when I try to run it:

Traceback (most recent call last): File "python", line 23, in TypeError: 'str' object does not support item assignment

gameon67
  • 3,981
  • 5
  • 35
  • 61
  • See the [help for `random.shuffle()`](https://docs.python.org/2/library/random.html#random.shuffle): Shuffle the sequence x **in place**. It modifies the existing sequence in place; doesn't return a new one. – Selcuk Jan 11 '19 at 00:37

1 Answers1

1

random.shuffle() can only shuffle lists. To do what you want, you must turn the letters of the word into a list.

I recommend doing this

import random
mysports= ["swimming" , "basketball" , "soccer" , "cross country" , 
"football" , "cross-country skiing"]
letters = mysports[0]
letters1 = mysports[1]
letters2 = mysports[2]
letters3 = mysports[3]
letters4 = mysports[4]
letters5 = mysports [5]
a = random.choice(mysports)
aList = []
for char in a:
    aList.extend(char)
random.shuffle(aList)
aString = ""
for char in aList:
    aString += char
print(aString)

It will do what you want and more efficiently.