[Tutor] Hi everyone

spir denis.spir at free.fr
Thu May 21 09:42:31 CEST 2009


Le Wed, 20 May 2009 18:25:07 -0700 (PDT),
Doug Reid <rnrcreid at yahoo.com> s'exprima ainsi:

> "The next line in the loop,
>    word = word[:position] + word[(position + 1):]
> 
> creates a new version of word minus the one letter at position position.
> Using slicing, the computer creates two new strings from word. The first
> slice, word[:position], is every letter up to, but not including,
> word[position]. The next slice, word[(position + 1):], is every letter
> after word[position]. These two string are joined together and assigned to
> word, which is now equal to its old self, minus the one letter
> word[position]."

>Can someone explain this in simpler terms? I'm sorry this
> is so lengthy for my first post:) 

It's confusing because abstract and without any example. In the case you wrote where the word is "python", the letter 'y', and so the position is 1, you get:
	word			"python"
	word[:position]		"p"
	word[position+1:]	"thon"
	glued together		"pthon"
Also, a confusing part of the program id the loop header:

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

In python, a container such as a string is considered 'False' when it's empty. Right? So that the loop header above is equivalent to:
    while len(word) > 0:
and the loop will stop when every letter has been extracted from the word.

Denis
------
la vita e estrany


More information about the Tutor mailing list