1

I'm trying to figure out a way to search though a 2D array to find a certain word and then replacin that word.

For example:

pets = [['I', 'have', 'a', 'cat'], ['She', 'has', 'a', 'pet', 'cat']]

I need a way to search for the word 'cat' and replace it with the word 'dog'.

3
  • and what have you tried? because so far it sounds like you are passing over homework. Commented Sep 6, 2017 at 16:03
  • Is it only 2 sentences in pets or there are more sentences? Commented Sep 6, 2017 at 16:11
  • 1
    So far I've tried using indexing the position but I wanted another way in case the words I'm looking for are'nt in the same position each time. And as for the second question, it depends on the user input. Commented Sep 6, 2017 at 16:24

2 Answers 2

5

You can use a list comprehension to check all elements, and replace those that are 'cat' with 'dog' :

pets = [['I', 'have', 'a', 'cat'], ['She', 'has', 'a', 'pet', 'cat']]

new_pets = [[p if p.lower()!='cat' else 'dog' for p in s] for s in pets]
print(new_pets) # => [['I', 'have', 'a', 'dog'], ['She', 'has', 'a', 'pet', 'dog']]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks again for the help!
Glad to help :).
0

Using list comprehension:

pets = [[val.replace('cat', 'dog') for val in row] for row in pets]

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.