Home > Blockchain >  Can I replace a word in a string using a for loop?
Can I replace a word in a string using a for loop?

Time:04-25

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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'
  • Related