In the code below, the only part I'M having trouble with is word[position]. I know this is something really simple but I've always had trouble understanding these kinds of statements. I know that it prints a random letter (position) from (word). What I don't know is why or how it does that. That's the part that never seems to get explained to me. How can you just put [] around part of a statement and everything just work right? Thanks. Please don't give me an answer like "because that's what's it mad to do. Explain it to me.

# Random Access
# Demonstrates string indexing

import random

word = "index"
print "The word is: ", word, "\n"

high = len(word)
low = -len(word)

for i in range(10):
    position = random.randrange(low, high)
    print "word[", position, "]\t", word[position]

raw_input("\n\nPress the enter key to exit.")

Running a little test program will help you a lot ...

word = "index"

# print first character of word at index=0
# index is zero based
print word[0]  # i

# print third character of word at index=2
# since the index is zero based you count 0, 1, 2
print word[2]  # d

# to print the last character you can go from the end using index=-1
print word[-1]  # x
# or use index=4
print word[4]  # x

# what to you think this would give?
# (count 4 index numbers from the end)
print word[-4]

Don't be afraid to test things out, I promise that your computer will not go up in smoke!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.