pythonarray-algorithms

Replace all occurances of a number in a matrix python


The input is a multi-line string containing the matrix:

input = '''22 13 17 11  0
 8  2 23  4 24
21  9  7 16  7
 6 10  3  7  5
 1 12 20 15 19'''

I have to replace all the occurrences of, let's say 7 with -1. So the output array would be:

output = '''22 13 17 11  0
 8  2 23  4 24
21  9  -1 16  -1
 6 10  3  -1  5
 1 12 20 15 19'''

Solution

  • You could keep it in string format and simply use a word-separator regex and sub all the specific numbers you want:

    import re
    
    s = '''22 13 17 11  0
     8  2 23  4 24
    21  9  7 16  7
     6 10  3  7  5
     1 12 20 15 19'''
    
    num = 7
    target = -1
    print(re.sub(rf'\b{num}\b', str(target), s))
    

    Will give:

    22 13 17 11  0
     8  2 23  4 24
    21  9  -1 16  -1
     6 10  3  -1  5
     1 12 20 15 19