1

I want to replace the item in a list that contains a certain substring. In this case the item the contains "NSW" (capitals are important) in any form should be replaced by "NSW = 0". It doesn´t matter if the original entry reads "NSW = 500" or "NSW = 501". I can find the list item but somehow i can not find the postion in the list so i could replace it? This is what i came up with, but i replaces all items:

from __future__ import division, print_function, with_statement
my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]
for index, i in enumerate(my_list):
    if any("NSW" in s for s in my_list):
        print ("found")
        my_list[index]= "NSW = 0"
print (my_list)  
Mahesh Karia
  • 2,045
  • 1
  • 12
  • 23
NorrinRadd
  • 545
  • 6
  • 21

3 Answers3

3

Simple list comprehension:

>>> ["NSW = 0" if "NSW" in ele else ele for ele in l]

#driver values :

IN :    l = ["abc 123", "acd 234", "NSW = 500", "stuff", "morestuff"]
OUT : ['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
1

any won't give you the index and it will always be true at each iteration. So drop it...

Personally I'd use a list comprehension with a ternary to decide to keep the original data or replace by NSW = 0:

my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]

result = ["NSW = 0" if "NSW" in x else x for x in my_list]

result:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Another solution: code:

from __future__ import division, print_function, with_statement
my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]
for index in xrange(len(my_list)):
    if "NSW" in my_list[index]:
        my_list[index] = "NSW = 0"

print (my_list)  

output:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']

or you can use list comprehension for purpose as follows:

code:

my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]

print ["NSW = 0" if "NSW" in _ else _ for _ in my_list]

output:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']
Mahesh Karia
  • 2,045
  • 1
  • 12
  • 23