Add a space before the \d+.
>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
>>> s = re.sub(" \d+", " ", s)
>>> s
'This must not b3 delet3d, but the number at the end yes '
Edit: After looking at the comments, I decided to form a more complete answer. I think this accounts for all the cases.
s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)
Answer from oneporter on Stack OverflowAdd a space before the \d+.
>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
>>> s = re.sub(" \d+", " ", s)
>>> s
'This must not b3 delet3d, but the number at the end yes '
Edit: After looking at the comments, I decided to form a more complete answer. I think this accounts for all the cases.
s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)
Try this:
"\b\d+\b"
That'll match only those digits that are not part of another word.
python - Removing numbers from string - Stack Overflow
Python Regex remove numbers and numbers with punctaution - Stack Overflow
nltk - Strip Numbers From String in Python - Stack Overflow
python - Using regEx to remove digits from string - Stack Overflow
Would this work for your situation?
>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'
This makes use of a list comprehension, and what is happening here is similar to this structure:
no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
if not i.isdigit():
no_digits.append(i)
# Now join all elements of the list with '',
# which puts all of the characters together.
result = ''.join(no_digits)
As @AshwiniChaudhary and @KirkStrauser point out, you actually do not need to use the brackets in the one-liner, making the piece inside the parentheses a generator expression (more efficient than a list comprehension). Even if this doesn't fit the requirements for your assignment, it is something you should read about eventually :) :
>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'
And, just to throw it in the mix, is the oft-forgotten str.translate which will work a lot faster than looping/regular expressions:
For Python 2:
from string import digits
s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'
For Python 3:
from string import digits
s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'
You can use:
>>> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)"
>>> print re.sub(r'\b\d+(?:\.\d+)?\s+', '', line)
https://en.wikipedia.org/wiki/Dictionary_(disambiguation)
Regex \b\d+(?:\.\d+)?\s+ will match an integer or decimal number followed by 1 or more spaces. \b is for word boundary.
Here's a non-regex approach, if your regex requirement is not entirely strict, using itertools.dropwhile:
>>> ''.join(dropwhile(lambda x: not x.isalpha(), line))
'https://en.wikipedia.org/wiki/Dictionary_(disambiguation)'
Yes, you can use a regular expression for this:
import re
output = re.sub(r'\d+', '', '123hello 456world')
print output # 'hello world'
str.translate should be efficient.
In [7]: 'hello467'.translate(None, '0123456789')
Out[7]: 'hello'
To compare str.translate against 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
Why not just use word boundaries?
\b\d+\b
Here is an example:
>>> import re
>>> words = ['python 3', 'python3', '1something', '2', '434', 'python 35', '1 ', ' 232']
>>> for word in words:
... print("'{}' => '{}'".format(word, re.sub(r'\b\d+\b', '', word)))
...
'python 3' => 'python '
'python3' => 'python3'
'1something' => '1something'
'2' => ''
'434' => ''
'python 35' => 'python '
'1 ' => ' '
' 232' => ' '
Note that this will not remove spaces before and after. I would advise using strip(), but if not you can probably do \b\d+\b\s* (for space after) or something similar.
You could just split the words and remove any words that are digits which is a lot easier to read:
new = " ".join([w for w in s.split() if not w.isdigit()])
And also seems faster:
In [27]: p = re.compile(r'\b\d+\b')
In [28]: s = " ".join(['python 3', 'python3', '1something', '2', '434', 'python
...: 35', '1 ', ' 232'])
In [29]: timeit " ".join([w for w in s.split() if not w.isdigit()])
100000 loops, best of 3: 1.54 µs per loop
In [30]: timeit p.sub('', s)
100000 loops, best of 3: 3.34 µs per loop
It also removes the space like your expected output:
In [39]: re.sub(r'\b\d+\b', '', " 2")
Out[39]: ' '
In [40]: " ".join([w for w in " 2".split() if not w.isdigit()])
Out[40]: ''
In [41]: re.sub(r'\b\d+\b', '', s)
Out[41]: 'python python3 1something python '
In [42]: " ".join([w for w in s.split() if not w.isdigit()])
Out[42]: 'python python3 1something python'
So both approaches are significantly different.
The pattern '1-9' will match the string 1-9. If you want to specify a set of characters, you should enclose it with []:
print(re.sub('[1-9]', '', 'Name 1with 12numbers'))
# >> Name with numbers
You can either use \d+ to remove digits:
import re
firstname = input("enter first name:")
lastname = input("enter last name:")
firstname = re.sub('\d+', '', firstname)
lastname = re.sub('\d+', '', lastname)
print(lastname, firstname)
Or use [0-9]:
import re
firstname = input("enter first name:")
lastname = input("enter last name:")
firstname = re.sub('[0-9]', '', firstname)
lastname = re.sub('[0-9]', '', lastname)
print(lastname, firstname)
Output:
enter first name:Hello12
enter last name:World23
World Hello