0

I have some strings like 'english100' and 'math50'. How can I convert them to a dictionary such as:

{'english': 100, 'math': 50}.

I have tried:

re.split(r'(?=\d)'

However, that does not work.

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
magicyang
  • 453
  • 1
  • 5
  • 14
  • 1
    Why do you think it doesn't work? – Alex L Jan 31 '13 at 03:56
  • @AlexL: This is a very strage limitation of Python. [It doesn't split on zero-length matches](http://stackoverflow.com/questions/2713060/why-doesnt-pythons-re-split-split-on-zero-length-matches), unlike any other regex flavor I know. And that's something you need to look hard for in the documentation. – Tim Pietzcker Jan 31 '13 at 06:22
  • @TimPietzcker Interesting, thanks for the link – Alex L Jan 31 '13 at 06:25

1 Answers1

3

If your strings are that simple, I'd probably do something like this:

d = dict()
d.update(re.findall(r'([a-zA-Z]+)(\d+)',"english100"))

Or another way (if you have multiple occurrences in the same string):

>>> dict(x.groups() for x in re.finditer(r'([a-zA-Z]+)(\d+)',"english100spanish24"))
{'spanish': '24', 'english': '100'}
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Hi, in your `re.findall` function, what does the little `r` do in front of the string pattern? – LWZ Jan 31 '13 at 16:28
  • 1
    @LWZ -- It makes it a "raw" string. In other words, it prevents python from interpreting usual escape seqences (such as `'\n'` which python usually translates to newline). – mgilson Jan 31 '13 at 16:34