Mish
Mish

Reputation: 53

Function replace( ) doesn't seem to be working

This is my homework problem:

Write a sequence of statements that produce a copy of a, named newA, in which characters ’.’, ’,’, ’;’, and ’\n’ have been replaced by blank spaces.

And I used the function replace( ) to do this, but when I executed newA, the output was a, not the replacement.

This is what I've done so far:

a = ' ' 'It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...' ' '

newA = a.replace('.', ' ')

newA = a.replace(',', ' ')

newA = a.replace(';', ' ')

newA = a.replace('\n', ' ')

Why isn't it working and how can I get it to work?

Upvotes: 0

Views: 77

Answers (3)

SM Abu Taher Asif
SM Abu Taher Asif

Reputation: 2331

After first time use the newA because replaced string assigned to newA:

newA = a.replace('.', ' ')
newA = newA.replace(',', ' ')
newA = newA.replace(';', ' ')

newA = newA.replace('\n', ' ')

Upvotes: 3

safokoi
safokoi

Reputation: 74

I think you should do it in a that way:

a = ' ' 'It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...' ' '

newA = a.replace('.', ' ')  
newA = newA.replace(',', ' ')    
newA = newA.replace(';', ' ')    
newA = newA.replace('\n', ' ')

or

a = ' ' 'It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...' ' '

newA = a.replace('.', ' ').replace(',', ' ').replace(';', ' ').replace('\n', ' ')

In your example you are repeatedly using replace on initial 'a' variable.

Upvotes: 2

J Lossner
J Lossner

Reputation: 139

You are performing the operation on the original string, a. You need to change the last three replacements from a.replace to newA.replace.

Upvotes: 2

Related Questions