Reputation: 37886
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?
Upvotes: 0
Views: 202
Reputation: 82470
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)
Upvotes: 1
Reputation: 2475
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 .
Upvotes: 1
Reputation: 6240
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
Upvotes: 2
Reputation: 113965
>>> 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']
Upvotes: 3