0

I have a string:

"23423 NewYork"

I want only NewYork from it. I could chop it into pieces, but the order can be different like "newyork 23244" etc..

what is the best way of extracting string from string which has also numbers in it?

3
  • 2
    Can you provide a better specification of what the input could look like and what the output should be? What if the input is "New York 1234"? What if it's "New York"? What if it's "New 1234 York"? What if it's the complete text of Hamlet? Commented Dec 17, 2013 at 10:24
  • 1
    Is it always divided in two or can they be mixed like "232 NewYork 123131 City"? Commented Dec 17, 2013 at 10:24
  • It can also be "new 2635 york" or "new york" Commented Dec 17, 2013 at 13:10

4 Answers 4

3
>>> s = "23423 NewYork"
>>> [sub for sub in s.split() if all(c.isalpha() for c in sub)]
['NewYork']
>>> s = "NewYork 23423"
>>> [sub for sub in s.split() if all(c.isalpha() for c in sub)]
['NewYork']
Sign up to request clarification or add additional context in comments.

2 Comments

I liked this one the most, but I can't help put put in an itertools solution here as well.
@doniyor: yup! give it a shot ;]
2
import re
s = "23423 NewYork"
m = re.findall('NewYork', s)

nah?

import re
s = "23423 NewYork"
m = re.findall(r'[^\W\d]+', s)

more general case

3 Comments

what does nah mean?
shortcut for "would it be suitable"
would that not be "wibs"?
1
from re import sub

s= "23423 NewYork"
sub('\d',"",s).strip()

This should do what you need.

\d removes all digits from the string and strip() should remove any extra spaces .

Comments

1

You may also try the following using itertools:

from itertools import takewhile, dropwhile

a = "23423 NewYork"
b = "NewYork 23423"


def finder(s):
    if s[0].isdigit():
        return "".join(dropwhile(lambda x: x.isdigit() or x.isspace(), s))
    else:
        return "".join(takewhile(lambda x: not x.isdigit() or x.isspace(), s))

if __name__ == '__main__':
    print finder(a)
    print finder(b)

3 Comments

Does this also extract "new 233 york"?
@doniyor Was it supposed to? I did not see that in your specification. But to answer your question, no it will not work.
Oh yeah sorry i forgot to mention it... I will work on it later then, thanks in tons anyway for your help.. waiting for train in trainstation :)

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.