Emma Lim
Emma Lim

Reputation: 161

How to replace specific string value to another in python list?

I want to write a code that replaces a certain string '-1' with '0' on the list. But I'm having a hard time writing if statements.

list = [-1, 1, -1]
if '-1' in list:
   code that replace -1 to 0   <--- What I want to add
else:
   pass

What I tried to do was the code below.

if i in list:
    temp = i.replace("-1","0")
    list.append(temp)
    print(list)
else:
    pass

But this code shows "NameError: name 'i' is not defined".

Upvotes: 0

Views: 84

Answers (3)

jester
jester

Reputation: 238

One thing you seem to be doing is mixing integers with strings: Your list contains integers: list = [-1, 1, -1] but you are trying to compare strings: temp = i.replace("-1","0")

Here is an example of replacing a list of integers and a list of strings:

list a is integers and list b is strings:

a= [1, 2, 3, 4, -1, 1, 2, -1, 4, 5, 1]

for i in range(0,len(a)):
    print(a[i])
    if(a[i]==-1):
        print("replace")
        a[i]=0
print(a)

b= ["1", "2", "3", "4", "-1", "1", "2", "-1", "4", "5", "1"]

for i in range(0,len(b)):
    print(b[i])
    if(b[i]=="-1"):
        print("replace")
        b[i]="0"
print(b)

Upvotes: 1

user15801675
user15801675

Reputation:

You can use enumerate and replace with index

list2 = [-1, 1, -1]
for i,j in enumerate(list2):
    if j==-1:
       list2[i]=0
print(list2)

Upvotes: 1

ThePyGuy
ThePyGuy

Reputation: 18406

You can use list-comprehension and take 0 if list item is -1 else just take the list item. Also as a side note, don't use list for variable name:

>>> [0 if i==-1 else i for i in List]
[0, 1, 0]

Upvotes: 3

Related Questions