-1

I want to convert a string

'[["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-07-03", "iPhone", 6347956, 187131, "1140332034.00000"], ["2018-07-03", "PC", 4413057, 166795, "1396042900.00000"], ["2018-07-03", "Android Mobile", 3840367, 107720, "639188845.00000"]]'

into a list of lists .

I tried something like this .

def str_to_list(raw_str):
    ll =[]
    raw_str = raw_str[1:-1]
    pp1 = raw_str.split("],")
    for i in pp1:
        date , dc , visit, order, gms  = i.strip().split(",")
        print(date[2:-1] , dc[2:-1] , int(visit), int(order), gms[2:-1] )
Kunal Kakade
  • 87
  • 1
  • 9

1 Answers1

1
>>> a = '[["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-07-03", "iPhone", 6347956, 187131, "1140332034.00000"], ["2018-07-03", "PC", 4413057, 166795, "1396042900.00000"], ["2018-07-03", "Android Mobile", 3840367, 107720, "639188845.00000"]]'
>>> import ast
>>> x = ast.literal_eval(a)
>>> x
[['2018-06-27', 'iPhone', 6332817, 174833, '1060303510.00000'], ['2018-06-27', 'PC', 4470497, 156399, '1251722217.00000'], ['2018-06-27', 'Android Mobile', 3912827, 104684, '591207335.00000'], ['2018-06-27', 'iPhone', 6332817, 174833, '1060303510.00000'], ['2018-06-27', 'PC', 4470497, 156399, '1251722217.00000'], ['2018-06-27', 'Android Mobile', 3912827, 104684, '591207335.00000'], ['2018-07-03', 'iPhone', 6347956, 187131, '1140332034.00000'], ['2018-07-03', 'PC', 4413057, 166795, '1396042900.00000'], ['2018-07-03', 'Android Mobile', 3840367, 107720, '639188845.00000']]
>>> 
>>> x[0]
['2018-06-27', 'iPhone', 6332817, 174833, '1060303510.00000']
>>> 

ast.literal_eval:

With ast.literal_eval, you can safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Pankaj Singhal
  • 12,388
  • 7
  • 37
  • 74