doniyor
doniyor

Reputation: 37886

I want to extract string from a string that also contains numbers - python

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

Answers (4)

Nafiul Islam
Nafiul Islam

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

Mevin Babu
Mevin Babu

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

rook
rook

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

inspectorG4dget
inspectorG4dget

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

Related Questions