Home > Enterprise >  Remove first 5 from numbers in a list?
Remove first 5 from numbers in a list?

Time:01-09

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?

CodePudding user response:

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.

CodePudding user response:

Another solution:

s = [int(str(x)[:str(x).index("5")]   str(x)[str(x).index("5")   1:]) for x in s]
  • Related