-4

i have some problem to strip '[' at my string (read from file). code

data = open(Koorpath1,'r')
for x in data:
    print(x)    
    print(x.strip('['))

result

[["0.9986130595207214","26.41608428955078"],["39.44521713256836","250.2412109375"],["112.84327697753906","120.34269714355469"],["260.63800048828125","15.424667358398438"],["273.6199645996094","249.74160766601562"]]

"0.9986130595207214","26.41608428955078"],["39.44521713256836","250.2412109375"],["112.84327697753906","120.34269714355469"],["260.63800048828125","15.424667358398438"],["273.6199645996094","249.74160766601562"]]

Desired output :

"0.9986130595207214","26.41608428955078","39.44521713256836","250.2412109375","112.84327697753906","120.34269714355469","260.63800048828125","15.424667358398438","273.6199645996094","249.74160766601562"

Thanks

Hearner
  • 2,711
  • 3
  • 17
  • 34
  • 1
    `strip` removes characters *at the start or end of the string* only. Looks like it does exactly what it's supposed to. If you want to remove characters in the middle as well, you need `replace`. But really, what for? This looks like JSON and you should probably `json.loads` it. – deceze Aug 10 '18 at 07:55
  • it's all string "[[ ... ]]". Type – Sufyan saori Aug 10 '18 at 07:56
  • What is your desired output ? – Hearner Aug 10 '18 at 07:56
  • @deceze Oh thanks, yes it's json data that i dump (save) at a file.Any suggest ? – Sufyan saori Aug 10 '18 at 07:57
  • @Hearner like that "0.9986130595207214","26.41608428955078","39.44521713256836","250.2412109375","112.84327697753906","120.34269714355469","260.63800048828125","15.424667358398438","273.6199645996094","249.74160766601562" – Sufyan saori Aug 10 '18 at 07:58

2 Answers2

0

It strips the first two '[', it seems you have one long string, you have to split it first.

datalist = data.split[',']
for x in datalist:
    # code here

If you don't want to split it and have it all in one string you need replace not strip (strip only works at the end and the beginning.

data = data.replace('[','')
Bernhard
  • 1,253
  • 8
  • 18
0

If the data is JSON, then parse it into a Python list and treat it from there:

from itertools import chain
import json

nums = json.loads(x)
print(','.join('"%s"' % num for num in chain.from_iterable(nums)))

chain.from_iterable helps you "flatten" the list of lists and join concatenates everything into one long output.

deceze
  • 510,633
  • 85
  • 743
  • 889