我有一个输入字符串:
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
并输出相应的输出:
[
'"testing"',
'"0.8841"',
'"642000.0"',
'"80.014521"',
'"-60.940653"',
'"4522126666"',
'"1500854400"',
'""',
'"1500842014000"',
'"name"',
'"80.014521"',
'"-60.996532"',
'"sampledevice"',
'"3"',
'"name"'
]
如何从列表中的每个元素中删除单引号?
答案 0 :(得分:5)
您需要应用strip
来删除字符串两边的引号。
dd = [x.strip('"') for x in data[i].split(',')]
说,你的循环似乎有一个索引问题。应该重写,例如:
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)
此时,
你会更好dd = ast.literal_eval(line)
还完美地使用csv
模块并输入list
(不需要传递文件句柄)(不要传递string
,因为它会产生一些奇怪的效果)
导入csv
for row in csv.reader(result.splitlines()):
print(row)
全部导致:
['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400']
['1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']
答案 1 :(得分:5)
将文本视为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)))
给你:
['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400', '', '1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']
答案 2 :(得分:4)
替换双引号:
>>> result.replace('"', '').split(',')
['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400', '', '1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']
答案 3 :(得分:4)
literal_eval是解决此问题的好方法
import ast
dd = [ast.literal_eval(i) for i in data]
答案 4 :(得分:1)
首先:输出字符串中没有单引号。你有什么是用双引号引用的字符串(可能存储在// ~/components/general/Page.vue
<template lang="pug">
div(id="page" class="align-center")
slot
</template>
文件中)。您在输出中看到的单引号实际上是确定字符串。所以:
csv
实际上是
'"some_string"'
第二:如果你想删除双引号,你可以这样做:
"some_string"
看下面的陈述,应该更清楚:
for item in data.split(","):
print(item.strip('"'))
答案 5 :(得分:1)
虽然声明很奇怪。他不想删除单引号吗?为什么每个人都发布删除双引号的答案。
这是我的建议:
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")
s = str(data)[2:-2] #Convert to a string, and delete [' and ']
for dd in s.split(','):
print dd
结果:
"testing"
"0.8841"
"642000.0"
"80.014521"
"-60.940653"
"4522126666"
"1500854400"
""
"1500842014000"
"name"
"80.014521"
"-60.996532"
"sampledevice"
"3"
"name"