Social Coder
Social Coder

Reputation: 103

List Slicing in Python 2

I am working on the hangman lessons in Invent with Python. For hours I am trying to understand the 2nd and 3rd line in the for loop below.

for i in range(len(secretWord)):
    if secretWord[i] in correctLetters:
        blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

I am aware it is list slicing, but while I do know what list slicing is, I don't get why the + operator is used.

Appreciate anyone explaining this.

Upvotes: 1

Views: 227

Answers (3)

thefourtheye
thefourtheye

Reputation: 239683

It is to concatenate the strings.

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

It will concatenate the blank string till i, character at i of secretWord and the blank string from i + 1 till the end.

Example:

blanks = "Welcome"
secretWord = "WELCOME"
i = 3
print blanks[:i] + secretWord[i] + blanks[i+1:]

Will print

WelCome

So basically the above seen line replaces character at i of blank with the character at i of secretWord.

Upvotes: 5

TerryA
TerryA

Reputation: 60024

The + is used as it would normally be used for - addition.

for i in range(len(secretWord)): loops through [0, 1, ... len(secretWord)] assigning i to each item every loop.

So in the first loop, blanks = blanks[:i] + secretWord[i] + blanks[i+1:] is :

blanks = blanks[:0] + secretWord[0] + blanks[0+1:]

Aka:

blanks = blanks[:0] + secretWord[0] + blanks[1:]
#                                            ^ 0 + 1 == 1

If you mean the + in between each slice, that is used for string concatenation:

>>> print 'hello ' + 'world'
hello world

Upvotes: 2

Simon
Simon

Reputation: 10841

When used with strings, the + operator in Python concatenates the strings.

Upvotes: 1

Related Questions