w3resource

Python: Concatenate the consecutive numbers in a given string

Python Regular Expression: Exercise-54 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/re/python-re-exercise-54.php