juanman
juanman

Reputation: 147

How to concatenate only consecutive numbers in a string?

I have a string with text and numbers, for example:

string = "Hello this is 123 456 a string for test 12 345 678. I want to merge 12 34 56"

And I want to have only the consecutive numbers together, like this:

newString = "Hello this is 123456 a string for test 12345678. I want to merge 123456"

How can I detect the number, check if they are consecutive and concatenate them?

Thanks!

Upvotes: 2

Views: 624

Answers (2)

pault
pault

Reputation: 43494

Here's one way using regular expressions:

import re
text = "Hello this is 123 456 a string for test 12 345 678. I want to merge 12 34 56"
newText = re.sub(r"(?<=\d)\s(?=\d)", '', text)
print(newText)
#'Hello this is 123456 a string for test 12345678. I want to merge 123456'

Explanation

What we're doing is replacing any spaces surrounded by digits with an empty string.

  • (?<=\d) means positive look-behind for a digit (\d)
  • \s means match a space character
  • (?=\d) means positive look-ahead for a digit

Upvotes: 4

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With re.sub() function and specific regex pattern:

import re

s =  "Hello this is 123 456 a string for test 12 345 678. I want to merge 12 34 56"
result = re.sub(r'(\d+)\s+(\d+?)', '\\1\\2', s)

print(result)

The output:

Hello this is 123456 a string for test 12345678. I want to merge 123456

Upvotes: 3

Related Questions