Varun Kushwaha
Varun Kushwaha

Reputation: 11

Can I replace a word in a string using a for loop?

I want to replace poor with good

MyStr2 = "I am poor"
MyLis = MyStr2.split(" ")

for i in range(MyLis):
    if MyLis[i] == "poor":
        MyLis[i] = "Good"



a = " ".join(MyLis)
print(a)

But it shows a error:
Traceback (most recent call last): File "e:\codes\learning\String.py", line 32, in for i in range(MyLis): TypeError: 'list' object cannot be interpreted as an integer

Upvotes: 1

Views: 1421

Answers (5)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24163

range should be used with len(MyLis), as others have said, as it expects an integer.

However, I'd rather do it the following way.

You can enumerate the indices of all the values in your sequence (list):

for index, value in enumerate(MyLis):
    if value == 'poor':
        MyLis[index] = 'Good'

Upvotes: 1

Sriram A
Sriram A

Reputation: 1

a="I am poor"
a1=a.split(" ")
for i in a1:
    if i=="poor":
        i="Good"
    print(i,end=" ")

Upvotes: 0

cards
cards

Reputation: 4996

Iterate over the list of words and append each word which doesn't satisfy the criteria to a new string otherwise perform the replacement.

MyStr2 = "I am poor"
MyLis = MyStr2.split(" ")

myStr_new = ''
for word in MyLis:
    if word == "poor":
        myStr_new += "Good"
    else:
        myStr_new +=word

print(myStr_new)

In "comprehension form":

MyStr2 = "I am poor"
MyStr2_new = ' '.join("Good" if word == 'poor' else word for word in MyStr2.split(' '))

print(MyStr2_new)

Upvotes: 1

Adon Bilivit
Adon Bilivit

Reputation: 27315

By using a dictionary, your code will be easily extensible for additional replacements. For your simple case:

MyStr2 = "I am poor"
d = {'poor': 'Good'}

print(' '.join(d.get(t, t) for t in MyStr2.split()))

Output:

I am Good

In this way you could add additional replacements to d without modifying anything else in the code

Upvotes: 2

JRiggles
JRiggles

Reputation: 6820

The problem is that range() is expecting an integer value and you’re giving it MyLis which is a list object.

You want to iterate over the length of your list, so you need to do range(len(MyLis)) instead.

Upvotes: 0

Related Questions