w3resource

Python: Concatenate the consecutive numbers in a given string


54. Concatenate Consecutive Numbers

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.

For more Practice: Solve these Related Problems:

  • Write a Python program to find and join consecutive number sequences in a string into a single number.
  • Write a Python script to search for space-separated digits that are consecutive and then concatenate them.
  • Write a Python program to merge consecutive numerical tokens in a text into one number and then print the modified string.
  • Write a Python program to transform a string by concatenating adjacent numbers if they are separated by a space.

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.