python-是否可以转换字符串并将其放入包含元组()的列表[]中? [英] python - Is it possible to convert a string and put it into a list [] containing tuple ()?

查看:137
本文介绍了python-是否可以转换字符串并将其放入包含元组()的列表[]中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,这两个是字符串,它们用制表符分隔。

For example, these two are the strings and they are separated by tabs.

2012-01-01 09:00 San Jose Men's服装214.05 Amex

是否可以将字符串转换为包含元组()的列表[]:

Is it possible to convert string to list [] containing tuple () :

[("2012-01-01", "09:00",    "San Jose", "Men's Clothing",   "214.05",   "Amex")]

如果是这样,我该怎么办?

If so, how can I do it?

预先感谢您!

编辑:更改标题

推荐答案

如果它是元素列表:

a = "2012-01-01 09:00    San Jose    Men's Clothing    214.05    Amex"
print [i for i in a.split("    ")]

结果:

['2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex']

元组:

a = "2012-01-01 09:00    San Jose    Men's Clothing    214.05    Amex"
print [tuple(i for i in a.split("    "))]

结果:

[('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex')]

如果您有多行字符串:

a = """2012-01-01 09:00    San Jose    Men's Clothing    214.05    Amex
2012-01-01 09:00    San Jose    Men's Clothing    214.05    Amex
2012-01-01 09:00    San Jose    Men's Clothing    214.05    Amex
2012-01-01 09:00    San Jose    Men's Clothing    214.05    Amex
2012-01-01 09:00    San Jose    Men's Clothing    214.05    Amex"""


print [tuple(j.split("    ")) for j in a.split("\n")]

结果:

[('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex')]

这篇关于python-是否可以转换字符串并将其放入包含元组()的列表[]中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆