geds133
geds133

Reputation: 1485

for loop iterable not overwriting original

I am trying to find all fullstops in a body of text and create a whitespace in from of them. I am only allowed to use for loops or I would use regular expression. I can't understand why the following for-loop does not replace the original letter with my new assignment. My code is as follows:

text = 'I have a ruler and bought for 25 gpb.'

text_split = text.split()

for word in text_split:
    for letter in word:
        if letter == '.':
            letter = ' .'

If anyone could help then it would be greatly appreciated

Upvotes: 1

Views: 138

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155674

letter = ' .' just rebinds the name letter to a different string. The original object bound to letter is unchanged (and can't be changed even in theory; str is an immutable type). A similar problem prevents changing the original str in text_split bound to word on each loop.

For this specific case, you just want:

text_split = [word.replace('.', ' .') for word in text_split]

or the slightly longer spelled out version (that modifies text_split in place instead of replacing it with a new list of modified str):

for i, word in enumerate(text_split):
    text_split[i] = word.replace('.', ' .')

Upvotes: 1

Related Questions