Remove first 5 from numbers in a list?

Question:

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?

Asked By: Somethingwhatever

||

Answers:

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.

Answered By: Akshay Sehgal

Another solution:

s = [int(str(x)[:str(x).index("5")] + str(x)[str(x).index("5") + 1:]) for x in s]
Answered By: jesy2013
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.