[Tutor] Remove a number from a string

Kent Johnson kent37 at tds.net
Tue Aug 23 21:00:52 CEST 2005

Shitiz Bansal wrote:
> Hi,
> Suppose i have a string '347 liverpool street'.
> I want to remove all the numbers coming at the starting of the string.
> I can think of a few ways but whats the cleanest way to do it?

With str.lstrip():

 >>> '347 liverpool street'.lstrip('0123456789')
' liverpool street'

or, if you want to strip the space as well:

 >>> '347 liverpool street'.lstrip('0123456789 ')
'liverpool street'

With a regular expression:

 >>> import re
 >>> re.sub('^[0-9]+', '', '347 liverpool street')
' liverpool street'


 >>> re.sub('^[0-9 ]+', '', '347 liverpool street')
'liverpool street'

If you are doing this a lot my guess is that a compiled re will be faster but that's just a guess...


More information about the Tutor mailing list