0

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 print 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 [], or sometimes (), around part of a statement and everything just work right? Thanks.

# 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.")
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by jice
0

[ ] is generaly used for indexing (see the list, tuple or dictionary chapters in the doc).

mylist=[ 1,2,3,4,5,6]
print mylist[ 3]

> 4

If you see strings like some kind of char tuple (immutable list), everything appears to be very simple as it works exactly the same.

Here is a completely stupid example :

mystring="qsdmlkiuranvdfkls"
for i, ch in enumerate(sorted(mystring)):
    print i, ch, mystring[i]
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.