Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – How to split a string until an occurence of an integer?

In Python, I am trying to split a string until an occurence of an integer, the first occurence of integer will be included, rest will not.

Example strings that I will have are shown below:

SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 ---
SOME OTHER STRING (PARANTHESIS AGAIN) 5 --- 3
AND SOME OTHER (AGAIN) 2 1 4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And the outputs that I need for these examples are going to be:

SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2
SOME OTHER STRING (PARANTHESIS AGAIN) 5
AND SOME OTHER (AGAIN) 2

Structure of all input strings will be in this format. Any help will be appreciated. Thank you in advance.

I’ve basically tried to split it with using spaces (" "), but it of course did not work. Then, I tried to split it with using "—" occurence, but "—" may not exist in every input, so I failed again.
I also referred to this: How to split a string into a string and an integer?
However, the answer suggests to split it using spaces, so it didn’t help me.

>Solution :

It’s ideal case for regular expression.

import re

s = "SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 ---"
m = re.search(r".*?[0-9]+", s)
print(m.group(0))

Explanation:

  • .* matches any number of characters
  • ? tells to not be greedy (without it it will stop in last integer)
  • [0-9]+ – matches one or more digits

It can be done without regular expressions too:

result = []
for word in s.split(" "):
    result.append(word)
    if word.isdigit(): # it returns True if string can be converted to int
        break
print(" ".join(result))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading