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)  
2
  • If you are performing replacement by index, there's really no need for any. Commented Dec 20, 2017 at 12:11
  • 2
    Get rid of the any. Instead, use if "NSW" in i: Commented Dec 20, 2017 at 12:12

3 Answers 3

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

Comments

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']

1 Comment

I am sorry, i really didn´t find the linked thread
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']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.