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

How to split a string of numbers and letters into a list of strings and a list of numbers

Given a string containing a sequence of letters and numbers (such as):

"GHG-H89KKK90KKP"  

Do we have any way to split this string into two lists, one containing the letters and one containing the numbers?

["GHG-H", "KKK", "KKP"] 
[89,90]

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

>Solution :

Use re.findall from the re (regular expressions) library to find patterns in the string. The first expression (?i)[a-z|\-]+ finds all sequences of letters (ignoring case), it also includes hyphens (-). The second expression [0-9]+ finds all sequences of numbers in your string.

import re

string = "GHG-H89KKK90KKP"

print(re.findall("(?i)[a-z|-]+", string))
print(re.findall("[0-9]+", string))

Output:

['GHG-H', 'KKK', 'KKP']
['89', '90']
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