如何在python中的第二个字符匹配上拆分字符串?

时间:2016-03-13 18:46:47

标签: python string split

我在变量中输入了字符串:

query = 'name=Alan age=23, name=Jake age=24'

如何在name=Jake而不是name=Alan上拆分字符串? 不建议query.split(name=Alan),它在我的案例中不会起作用。

我需要先跳过name并继续搜索第二个,然后进行拆分的内容。那么,我该怎么做呢?

3 个答案:

答案 0 :(得分:1)

使用query.split(',')[1].split('name')

答案 1 :(得分:0)

You can try splitting on the comma and then on the spaces like so:

query = 'name=Alan age=23, name=Jake age=24'
query_split = [x.strip() for x in query.split(",")]
names = [a.split(" ")[0][5:] for a in query_split]
print(names)

['Alan', 'Jake']

With this you don't need multiple variables since all your names will be in the list names, you can reference them by names[0], names[1] and so on for any given number of names.

答案 2 :(得分:0)

试试这个:

query = 'name=Alan age=23, name=Jake age=24'
names = [y.split(" ")[0][5:] for y in (x.strip() for x in query.split(","))]
print(names)

输出:

['Alan', 'Jake']