-3

Can someone please explain to me what the last line of this loop does? It's a snippet from a word jumble program that is an example from a book I am learning from. Thank you.

import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
word = random.choice(WORDS)
correct = word
jumble = " "

while word:
  position = random.randrange(len(word))
  jumble += word[position]

  word = word[:position] + word[(position +1):]  

1 Answers1

2

It cuts out the character at index position:

>>> word = "python"
>>> position = 3
>>> 
>>> word[:position] + word[(position +1):]
'python'

Our string here was "python":

p  y  t  h  o  n
0  1  2  3  4  5
         ^

It therefore makes sense that for position = 3 the result is "python", with the 'h' missing.

In the future always try to test these things with a simplified example, usually they'll give you insight in to exactly what's going on.

See also: Python's slice notation

Community
  • 1
  • 1
arshajii
  • 123,543
  • 24
  • 232
  • 276
  • Thank you so much. I'm sorry for bothering you guys needlessly. I didn't think to do this. :-/ – Thomas Notaro Oct 27 '13 at 19:35
  • @ThomasNotaro Glad I could help. Don't forget to [accept an answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235). – arshajii Oct 27 '13 at 19:36