0

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".

1

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.