I have a string as the following:
s = 'ABC:10DEF:20'
I need to extract the numbers and assign it to the variables as:
ABC = 10
DEF = 20
How can I do this?
A simple regex to find all numerical values
import re
s = 'ABC:10DEF:20'
re.findall('[\d]{1,}',s)
I suggest splitting the string to a dictionary where the keys are the alpha letters and the values are the numbers.
>>> import re
>>> s = 'ABC:10DEF:20'
>>> d = dict(x.split(':') for x in re.split(r'(?<=\d)(?=\D)', s))
>>> d
{'ABC': '10', 'DEF': '20'}
Just use the .split()
built-in method in python. For example, you can say s = s.split(":")
and what it should throw is ["ABC", "10", "DEF", "20"]
. Then it is simply using indices to find what you need. To actually assign the ABC as a variable I don't know, but I think you should start with the .split()
hope this helps:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.