w3resource

Python: Concatenate the consecutive numbers in a given string


Write a Python program to concatenate the consecutive numbers in a given string.

Sample Solution:

Python Code:

import re
txt = "Enter at 1 20 Kearny Street. The security desk can direct you to floor 1 6. Please have your identification ready."
print("Original string:")
print(txt)
new_txt = re.sub(r"(?<=\d)\s(?=\d)", '', txt)
print('\nAfter concatenating the consecutive numbers in the said string:')
print(new_txt)

Sample Output:

Original string:
Enter at 1 20 Kearny Street. The security desk can direct you to floor 1 6. Please have your identification ready.

After concatenating the consecutive numbers in the said string:
Enter at 120 Kearny Street. The security desk can direct you to floor 16. Please have your identification ready.

Flowchart:

Flowchart: Regular Expression -  Concatenate the consecutive numbers in a given string.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to remove lowercase substrings from a given string.
Next: Write a Python program to convert a given string to snake case.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.