Python Python Basics (2015) Letter Game App Random Item

Dan Holroyd
Dan Holroyd
1,117 Points

Need help grabbing item from string

So I've stored the random number in the variable 'pick' and that's all well and good, but I can't remember the syntax for grabbing that position from the string, and what I have isn't working.
import random

def random_item(nasgul):
    pick = random.randint(0, len(nasgul)-1)
    return nasgul.index(pick)
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"

1 Answer

Manish Giri
Manish Giri
16,265 Points

For all iterables, like strings and lists, you specify the name of the iterable, and then the position in the iterable inside [ ] - so like my_string[3].