我有一个输入字符串:
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
Run Code Online (Sandbox Code Playgroud)
并将相应的输出为:
[
'"testing"',
'"0.8841"',
'"642000.0"',
'"80.014521"',
'"-60.940653"',
'"4522126666"',
'"1500854400"',
'""',
'"1500842014000"',
'"name"',
'"80.014521"',
'"-60.996532"',
'"sampledevice"',
'"3"',
'"name"'
]
Run Code Online (Sandbox Code Playgroud)
如何从列表中的每个元素中删除单引号?
你需要申请strip删除字符串两边的引号.
dd = [x.strip('"') for x in data[i].split(',')]
Run Code Online (Sandbox Code Playgroud)
那说,你的循环似乎有一个索引问题.应该重写,例如:
result = '"testing","0.8841","642000.0","80.014521","-60.940653","4522126666","1500854400"\n"1500842014000","name","80.014521","-60.996532","sampledevice","3","name"'
for line in result.splitlines():
dd = [x.strip('"') for x in line.split(',')]
print(dd)
Run Code Online (Sandbox Code Playgroud)
在这一点上,你会变得更好
dd = ast.literal_eval(line)
Run Code Online (Sandbox Code Playgroud)
还有csv一个list输入完全使用模块(不需要传递文件句柄)(不要传递string,因为它会产生一些奇怪的效果)
导入csv
import csv
for row in csv.reader(result.splitlines()):
print(row)
Run Code Online (Sandbox Code Playgroud)
所有导致:
['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400']
['1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']
Run Code Online (Sandbox Code Playgroud)
将文本视为CSV:
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)))
Run Code Online (Sandbox Code Playgroud)
给你:
['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400', '', '1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']
Run Code Online (Sandbox Code Playgroud)
拆分前替换双引号:
>>> result.replace('"', '').split(',')
['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400', '', '1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']
Run Code Online (Sandbox Code Playgroud)
literal_eval 是解决这个问题的好方法
import ast
dd = [ast.literal_eval(i) for i in data]
Run Code Online (Sandbox Code Playgroud)