I have an input string as:
result = '"testing","0.8841","642000.0","80.014521","-60.940653","4522126666","1500854400","","1500842014000","name","80.014521","-60.996532","sampledevice","3","name"'
data = result.split("\n")
i = 0
while i < len(data):
i = i +1
dd = data[i].split(',')
print dd
break
And the corresponding output as:
[
'"testing"',
'"0.8841"',
'"642000.0"',
'"80.014521"',
'"-60.940653"',
'"4522126666"',
'"1500854400"',
'""',
'"1500842014000"',
'"name"',
'"80.014521"',
'"-60.996532"',
'"sampledevice"',
'"3"',
'"name"'
]
How can I remove the single quotes from each element in the list?
To erase Quotes (“”) from a Python string, simply use the replace() command or you can eliminate it if the quotes seem at string ends.
Using sep keyword in print: If you just want to separate the items and print a list without the brackets and single quotes, then you don't need to specify the value of sep because it has a default value of whitespace.
Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.
Treat the text as a row from a CSV formatted file:
import csv
import StringIO
result = '"testing","0.8841","642000.0","80.014521","-60.940653","4522126666","1500854400","","1500842014000","name","80.014521","-60.996532","sampledevice","3","name"'
print next(csv.reader(StringIO.StringIO(result)))
Giving you:
['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400', '', '1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']
Python's StringIO()
function allows the text to be treated like a file allowing it to be passed to Python's CSV parser which is designed for parsing CSV files in this format. It can then correctly parse the text and return a list of items.
The returned data could then be further processed if needed to convert the text into numbers, i.e. integers or floats as appropriate. For example:
import csv
import StringIO
def convert(text):
try:
return int(text)
except ValueError:
pass
try:
return float(text)
except ValueError:
return text
result = '"testing","0.8841","642000.0","80.014521","-60.940653","4522126666","1500854400","","1500842014000","name","80.014521","-60.996532","sampledevice","3","name"'
values = [convert(value) for value in next(csv.reader(StringIO.StringIO(result)))]
print values
This would then return a list as follows:
['testing', 0.8841, 642000.0, 80.014521, -60.940653, 4522126666L, 1500854400, '', 1500842014000L, 'name', 80.014521, -60.996532, 'sampledevice', 3, 'name']
literal_eval is good solution for this issue
import ast
dd = [ast.literal_eval(i) for i in data]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With