Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading