0

I have some strings like -

1. "07870 622103"
2. "(0) 07543 876545"
3. "07321 786543 - not working"

I want to get the last 10 digits of these strings. like -

1. "07870622103"
2. "07543876545"
3. "07321786543"

So far I have tried-

a = re.findall(r"\d+${10}", mobilePhone)

Please help.

1
  • Your output contains 11 digits each. Commented Nov 28, 2012 at 10:03

2 Answers 2

3

It'll be easier just to filter your string for digits and picking out the last 10:

''.join([c for c in mobilePhone if c.isdigit()][-10:])

Result:

>>> mobilePhone = "07870 622103"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7870622103'
>>> mobilePhone = "(0) 07543 876545"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7543876545'
>>> mobilePhone = "07321 786543 - not working"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7321786543'

The regular expression approach (filtering everything but digits), is faster though:

$ python -m timeit -s "mobilenum='07321 786543 - not working'" "''.join([c for c in mobilenum if c.isdigit()][-10:])"
100000 loops, best of 3: 6.68 usec per loop
$ python -m timeit -s "import re; notnum=re.compile(r'\D'); mobilenum='07321 786543 - not working'" "notnum.sub(mobilenum, '')[-10:]"
1000000 loops, best of 3: 0.472 usec per loop
Sign up to request clarification or add additional context in comments.

Comments

2

I suggest using a regex to throw away all non-digit. Like so:

newstring = re.compile(r'\D').sub('', yourstring)

The regex is very simple - \D means non-digit. And the code above uses sub to replace any non-digit char with an empty string. So you get what you want in newstring

Oh, and for taking the last ten chars use newstring[-10:]

That was a regex answer. The answer of Martijn Pieters may be more pythonic.

1 Comment

The faster of the two is the more pythonic; yours is the faster approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.