-2

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):]  
Thomas Notaro
  • 35
  • 1
  • 5

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
  • 127,459
  • 24
  • 238
  • 287