Reputation: 793
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]
Upvotes: 1
Views: 441
Reputation: 483
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']
Upvotes: 8
Reputation: 919
I believe there is no straightforward way, but you an use the re
library.
For example:
import re
s = "GHG-H89KKK90KKP"
out = [c for c in re.split('\d', s) if c != '']
print(out)
the split gives you a list of the num characters by removing the '\D' non num (or non num characters by removing the nums using '\d'), and then the we delete the empty values. The print gives : ['GHG-H', 'KKK', 'KKP']
(for the use of '\d')
Upvotes: 0