简体   繁体   中英

How to replace single quotes that appear when using split() function

I have a string, list1 that I'm converting to a list in order to compare it with another list, list2 , to find common elements.

The following code works, but I need to replace ' with " in the final output, since it will be used in TOML front matter.

list1 = "a b c"
list1 = list1.split(" ")

print list1
>>> ['a','b','c']

list2 = ["b"]

print list(set(list1).intersection(list2))
>>> ['b']

**I need ["b"]**

New to python. I've tried using replace() and searched around, but can't find a way to do so. Thanks in advance.

I'm using Python 2.7.

Like any other structured text format, use a proper library to generate TOML values. For example

>>> import toml
>>> list1 = "a b c"
>>> list1 = list1.split(" ")
>>> list2 = ["b"]
>>> v = list(set(list1).intersection(list2))
>>> print(v)
['b']
>>> print(toml.dumps({"values": v}))
values = [ "b",]

made it

import json
l1 = "a b c"
l1 = l1.split(" ")

print(l1)


l2 = ["b"]

print(json.dumps(list(set(l1).intersection(l2))))

print(type(l1))

output:

['a', 'b', 'c']
["b"]
<type 'list'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM