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

Remove first 5 from numbers in a list?

I have a list with numbers like this :-

s = [5542, 5654, 7545]

The goal is to remove the first 5 from the number such that the resultant list is like this :-

s = [542, 654, 745]

What’s the best way to achieve the following without using any external libraries?

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 :

Try this with str.replace(old, new, count)

[int(str(i).replace('5','',1)) for i in s]
[542, 654, 745]

The str.replace(old, new, count) in this case has 3 parameters, where the count set to 1 will only replace the first instance of 5 it finds in the string.

Then you can convert it back to an integer.

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