Python

Moderators: None (Apply to moderate this forum)
Number of threads: 473
Number of posts: 1172

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Indexing Strings Posted by Garrett85 on 5 Oct 2009 at 11:16 PM
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, "\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.")

Report
Re: Indexing Strings Posted by bubbatremell on 8 Oct 2009 at 2:43 PM
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...
Report
Re: Indexing Strings Posted by Garrett85 on 8 Oct 2009 at 11:26 PM
Thanks for the help. I really appreciate it.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.