简体   繁体   中英

How to remove duplicating character from beginning of a string

I have a an array of human-entered numbers which contain random amount of zeros before actual number begins. guess example will say more:

entry_1="0000005452508"
entry_2="02965054"
entry_3="5487864"

I need to get the string after these duplicating zeros end, ie first entry should result in 5452508. Numbers of digits if not fixed. Lists are enormously huge, so I need something nice and fast to work here.

Any ideas appreciated.

lstrip does what you want:

entry_1 = "0000005452508".lstrip("0")
entry_2 = "02965054".lstrip("0")
entry_3 = "5487864".lstrip("0")

lstrip , as suggested by @dav1d is definitely the way to go.

With regex, you could use the following to accomplish the same:

> import re
> re.sub("^0+", "", "0000005452508")
"5452508"

I would go with .lstrip as has already been suggested, but if you really wanted a regex.

Sub leading zeroes with nothing:

re.sub(r'^0*', '', entry_1)

Good answers have already been provided, but all are creating a new sequence . To offer an alternative, since you have specified that your lists are huge and copying could thus be an issue, you should consider using itertools.dropwhile :

Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element.

For example:

import itertools
itertools.dropwhile(lambda x: x == '0', entry_1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM