Reputation: 1128
INPUT: "00012" / "00453403" / "0000000" / "123223"
OUTPUT: "12" / "453403" / "0" / "123223"
I can do it in 3 or more lines of code and now I feel dumb because I think there must be a way to do it in one line (lets's say 2 to be safe).
Can someone help to rise the number of beautiful code in the world ? :)
def remove_unnecessary_zero_in_the_beginning(nbr_as_str):
while len(nbr_as_str) > 1 and nbr_as_str[0] == "0":
nbr_as_str = nbr_as_str[1:]
return nbr_as_str
print(remove_unnecessary_zero_in_the_beginning("00012"))
Upvotes: 1
Views: 79
Reputation: 1
Say you have a list of the inputs ie : l1 = [ "00012" , "00453403" , "0000000" , "123223"]
Code can be :
l1 = [ "00012" , "00453403" , "0000000" , "123223"]
test = list(map(lambda x : x.strip('0') if int(x)!=0 else int(x),l1))
print(test)
Upvotes: 0
Reputation: 331
You could use this
i = ["00012","00453403","0000000","123223"]
o = ["{0:d}".format(int(e)) for e in l]
Output:
o
Out[8]: ['12', '453403', '0', '123223']
Upvotes: 0
Reputation: 77337
You could use a regular expression with a match group. This one matches all leading zeros then captures all digits after that. A \d*?
non-greedy match followed by \d
ensures that at least the last digit is always present, even if its 0.
import re
def remove_unnecessary_zero_in_the_beginning(nbr_as_str):
return re.match(r"0*(\d*?\d)$", t).group(1)
test = ["00012", "00453403", "0000000", "123223"]
for t in test:
print(remove_unnecessary_zero_in_the_beginning(t))
Upvotes: 0