python-3.x - 从python中的字符串中删除双引号
问题描述
希望我的输出不应该是字符串,而是我的代码将字符串返回给我。请查看我的以下代码,其中 z 是我的输出。我尝试了 regex、replace、strip、eval、ast.literal_eval 但到目前为止对我没有任何作用。
x = "'yyyymm'='202005','run_id'='51',drop_columns=run_id"
y = x.split(',')
print(y)
这将打印:
["'yyyymm'='202005'","'run_id'='51'","drop_columns=run_id"]`
但我想要:
['yyyymm'='202005','run_id'='51',drop_columns=run_id]
解决方案
x
is a string and if you split a string, you will get an array of strings. It is basically cutting it into pieces.
Your question is not really clear on what you want to achieve. If you want to have key-value-pairs, you'd need to split each token at the =
. This would give you something like this:
[('yyyymm', '202005'), ('run_id', '51'), ('drop_columns', 'run_id')]
But the items in the tuples would still be strings. If you want to have integers, you would need to cast them which is only possible if the strings consist of digits. It would not be possible to cast 'run_id'
to integer.
You can refer to this example. I'm not sure if that is 100% what you are looking for, but it should give you the correct idea.
x = "yyyymm=202005,run_id=51,drop_columns=run_id"
y = x.split(',')
tmp = []
for e in y:
tmp.append((e.split('=')[0], e.split('=')[1]))
out = []
for e in tmp:
if str.isnumeric(e[1]):
out.append((e[0], int(e[1])))
else:
out.append(e)
print(out)
This will give you:
[('yyyymm', 202005), ('run_id', 51), ('drop_columns', 'run_id')]
推荐阅读
- angular - Ionic 4 路由器链接和查询参数不起作用
- python - 为什么我得到一个正确的python请求(400 Bad Request)?
- webrtc - 服务器-客户端架构的最小 sdp
- flutter - 使用后端编程 Square 支付和 Flutter App
- c++ - Project1.exe 中 0x00007FFCA550A839 处的未处理异常:Microsoft C++ 异常:内存位置 0x0000002F82CFEF60 处的 std::bad_alloc。发生了
- java - 关于创建事务的控制器方法问题
- html - 带有 flexbox 的大型产品视图的产品列表
- vim - 如何在滚动条上启用高亮显示 VIM 中搜索结果的出现?
- gatsby - Gatsby 构建输出 css 使它变得混乱
- php - 如何避免序列化程序将双引号转义为 \u0022?