首页 > 解决方案 > 从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]

标签: python-3.x

解决方案


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')]


推荐阅读