Reputation: 77
I want to delete numbers contained in the text with Python. But I don´t want to delete the numbers that are part of a string.
For example,
strings = [ "There are 55 cars in 45trt avenue"
In this case 55
should be deleted, but not 45trt
, that should remain the same
Thanks in advance,
Upvotes: 0
Views: 33
Reputation: 521194
You could try searching for numbers which are surrounded by word boundaries:
inp = "There are 55 cars in 45trt avenue"
output = re.sub(r'\s*\b\d+\b\s*', ' ', inp).strip()
print(output)
This prints:
There are cars in 45trt avenue
The logic here is to actually replace with a single space, to ensure that the resulting string is still properly spaced. This opens an edge case for numbers which might happen to appear at the very beginning or end, leaving behind an extra space. To handle that, we trim using strip()
.
Upvotes: 2