Line numbers from a line in Python

Is there an efficient way to extract numbers from a string in python? Using nltk or basic python?

Thanks Ben

+5
source share
5 answers

Yes, you can use a regex for this:

import re output = re.sub(r'\d+', '', '123hello 456world') print output # 'hello world' 
+19
source

str.translate should be effective.

 In [7]: 'hello467'.translate(None, '0123456789') Out[7]: 'hello' 

To compare str.translate with re.sub :

 In [13]: %%timeit r=re.compile(r'\d') output = r.sub('', my_str) ....: 100000 loops, best of 3: 5.46 Β΅s per loop In [16]: %%timeit pass output = my_str.translate(None, '0123456789') ....: 1000000 loops, best of 3: 713 ns per loop 
+7
source

Try again.

 import re my_str = '123hello 456world' output = re.sub('[0-9]+', '', my_str) 
+3
source

Here we use a method using str.join() , str.isnumeric() and a generator expression that will work in 3.x:

 >>> my_str = '123Hello, World!4567' >>> output = ''.join(c for c in my_str if not c.isnumeric()) >>> print(output) Hello, World! >>> 

This will also work in 2.x if you use the unicode line:

 >>> my_str = u'123Hello, World!4567' >>> output = ''.join(c for c in my_str if not c.isnumeric()) >>> print(output) Hello, World! >>> 

Hm. Throw it in a paper clip and we will have a MacGyver episode.

Update

I know this was closed as a duplicate, but here is a method that works for both Python 2 and Python 3:

 >>> my_str = '123Hello, World!4567' >>> output = ''.join(map(lambda c: '' if c in '0123456789' else c, my_str)) >>> print(output) Hello, World! >>> 
+1
source

Another way to do what you ask is to add characters from one line to another new empty line using the for loop. A friendly reminder that strings are immutable. This is a more friendly approach that allows you to overcome the possible consequences of what may happen during repetition.

 def removeNumbersFromStrings(string): newString = "" for ch in string: if ch == '0' or ch == '1' or ch == '2' or ch == '3' or ch == '4' or ch == '5' or ch == '6' or ch == '7' or ch == '8' or ch == '9': newString = newString else: newString = newString + ch return newString 

Sometimes the easiest way to do something can really help when looking at your code later in the day, say, after a few months when you can change it.

+1
source

All Articles