Hangman question

E

eschneider92

I'm on chapter 9 of this guide to python: http://inventwithpython.com/chapter9.html but I don't quite understand why line 79 is what it is (blanks = blanks[:i] + secretWord + blanks[i+1:]). I particularly don't get the [i+1:] part. Any additional information and help would be greatly appreciated!
 
J

Joshua Landau

I'm on chapter 9 of this guide to python:
http://inventwithpython.com/chapter9.html but I don't quite
understand why line 79 is what it is (blanks = blanks[:i] + secretWord +
blanks[i+1:]). I particularly don't get the [i+1:] part. Any additional
information and help would be greatly appreciated!


First you should realise that this isn't actually great code by my
standards. There are quite a few un-idiomatic things done, but hopefully
the learning you get outweighs the things you have to unlearn ;).

That said, here's an explanation.

This loop:

for i in range(len(secretWord)): # replace blanks with correctly
guessed letters
if secretWord in correctLetters:
blanks = blanks[:i] + secretWord + blanks[i+1:]

wants to change blanks from a string like "____" to a string like "a_t_".
It has a companion string, secretWord, of the same length (such as "acts").

the "for i in range(len(secretWord)):" loop¹ goes through all the numbers
from 0 to 3 in this case.

"if secretWord in correctLetters:"³ takes the letter from position 0 to
3, which is each of the letters in the secret word in turn, so "a", "c",
"t" and "s" and checks if that letter is in correctLetters.

If it is, we want to do the transformation like "____" -> "a___" and "a___"
-> "a_t_".

This brings us to line 79.

blanks = blanks[:i] + secretWord + blanks[i+1:]â´

Let "blanks" be "a___". When i == 2, secretWord == "t" which we can
assume is in correctLetters.

"blanks[:2]" returns "a_" because you're slicing the string up to the
second stop. I don't know how slices have been taught but I'd been taught
like so:

[0]a[1]_[2]_[3]_[4]

so slicing from the start (by missing the start index in the slice) to 2
would return the "a" and "_".

"secretWord" returns "t" as before.

"blanks[i+1:]" == "blanks[2+1:]" == "blanks[3:]" so return the rest*after
skipping one*, so just "_". This means that the additions resolve to:

blanks = "a_" + "t" + "_"

which results in "a_t_".

Does this help?



¹ You should really use "for i, letter in enumerate(secretWord²):" but I'll
let it pass for simplicity.
² Really, "secret_word" is better than "secretWord", too, but w/e.
³ Better written as "if letter in guessed_letters:" given [1] and a
generalisation of [2].
â´ This is *really* bad practice. Not only is the string rebuilt every time
the loop happens but it's actually rebuilt in part about *three* times per
loop. In this case it's not a big deal, but don't write things like this.âµ
âµ You should probably use a mutable list which you "".join() OR replace
elements using an iterator (the second of those you can leave for later but
they're not that hard).
 
P

Peter Otten

I'm on chapter 9 of this guide to python:
http://inventwithpython.com/chapter9.html but I don't quite understand
why line 79 is what it is (blanks = blanks[:i] + secretWord +
blanks[i+1:]). I particularly don't get the [i+1:] part. Any additional
information and help would be greatly appreciated!


When you have a list with and want to replace the third item with something
else you can do it like this:
items = ["r", "e", "e", "d"]
items[2] = "a"
items
['r', 'e', 'a', 'd']

With a string that is not possible because strings cannot be modified (they
are "immutable"):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

You could try replace() to build a new string
'raad'

but that replaces all occurrences. So to manually replace th third character
you take the first two characters of the original
're'

then the characters after the third
'd'

and finally build the new string by putting the new character (or string) in
between:
'read'

A function to replace the n-th character would then look like this:
.... return s[:n] + replacement + s[n+1:]
....'reed'
 
D

Dave Angel

I'm on chapter 9 of this guide to python: http://inventwithpython.com/chapter9.html but I don't quite understand why line 79 is what it is (blanks = blanks[:i] + secretWord + blanks[i+1:]). I particularly don't get the [i+1:] part. Any additional information and help would be greatly appreciated!


(You're using googlegroups, which is painfully buggy. Just an alert
that some folks won't even see a message from googlegroups, because they
filter it out in protest.

If you join this mailing list with more conventional means, you can
avoid several problems.)

The syntax you're describing is called a slice. it works on strings,
and on lists, and some other places. For strings in particular, because
they are immutable, something that ought to be easy becomes a
strange-looking slice expression. it's worth taking the trouble to
figure out the patterns of those, so you can just recognize them without
too much thought.

And of course, asking here is one good first step for that.

A slice can specify up to 3 numeric values, which could be labeled as
start, end, and step, just like range. However, they're separated by
colons, rather than commas.

Go to the debugger (by just typing python at the command prompt, without
a script), and play a bit.

"abcdefg"[:3] is analogous to range(3), which is equivalent to
range(0,3). Those ranges produce a list containing 0, 1 and 2. So the
string slice produces the characters at those 3 positions. In other
words, "abc" (Remember Python is 99.9% zero-based).

(If on Python 3.x, use list(range(qqq)) to expand it out and actually
see the elements as a list)

"abcdefg"[4:] is analogous to range(4, 7) and produces 'efg'

Notice that character 3 is not in either string. The letter 'd' is
missing. So this particular pattern:

xxx[:i] + other + xxx[i+1:]

lets you replace the ith character with whatever's in "other". if it's
a single character, the net effect is just replacing the ith character
with a different one.

Does that help?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top