0

In Python, what is the most efficient and elegant way to convert string like this:

"(1, 89, 67, 23)"

to a real list? I know, that all elements are integers.

nekomimi
  • 1,310
  • 3
  • 10
  • 14

2 Answers2

1
>>>> a = "(1, 89, 67, 23)"
>>> a.strip('()').split(',')
['1', '89', '67', '23']

using regex:

>>>re.findall('\d+',a)
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
1

With regex:

import re
l = [int(i) for i in re.findall(r'(\d+)', "(1, 89, 67, 23)")]
print l

I use the r just for code-highighting for regex. But here is a good explanation for this: What exactly do "u" and "r" string flags do in Python, and what are raw string literals?

Community
  • 1
  • 1
Vincent Beltman
  • 2,064
  • 13
  • 27