Indexing Strings - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Indexing Strings

Garrett85Garrett85 Posts: 168Member
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 [] 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, "

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

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


Press the enter key to exit.")[/code]


  • bubbatremellbubbatremell Posts: 39Member
    I'm not quite sure how to explain this if you already have it written out as 'word' and 'position'. Given a string "word" and an integer "i", word[i] returns the letter in the ith position. Remember that Python is zero-indexed, though, so for the word "index", you have
    i -> 0
    n -> 1
    d -> 2
    e -> 3
    x -> 4
    Note that there is not position 5, even though len(word) == 5.

    Also, putting '-' in an index has a special meaning in Py. That makes your index start at the end of the word instead of at the beginning. So, you get

    x -> -1
    e -> -2
    d -> -3
    n -> -4
    i -> -5

    That's nice for when you need to get to the back of a string/list, but you don't know how long it is. I guess you could also use it to count backwards...
  • Garrett85Garrett85 Posts: 168Member
    Thanks for the help. I really appreciate it.
Sign In or Register to comment.