简体   繁体   中英

What's the most Pythonic way to remove a number from start of a string?

I have various strings

123_dog 2_fish 56_cat 45_cat_fish

There is always one number. Always a '_' after the number.

I need to remove the number and the underscore. I can use regex, but I wonder if there is some pythonic way that uses builtin methods?

(I'm an experienced coder - but new to Python.)

Assuming that there is always an underscore after the number, and that there is always exactly a single number, you can do this:

s = '45_cat_fish'
print s.split('_', 1)[1]
# >>> cat_fish

The argument to split specifies the maximum number of splits to perform.

Using split and join:

>>> a="45_cat_fish"
>>> '_'.join(a.split('_')[1:])
'cat_fish'

Edit: split can take a maxsplit argument (see YS-L answer), so '_'.join is unnecessary, a.split('_',1)[1]


Using find

>>> a[a.find('_')+1:]
'cat_fish'

Another way is:

s = "45_cat_fish"
print ''.join(c for c in s if c.isalpha() or c == '_')[1:]

gives cat_fish

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