python - 是否可以转换字符串并将其放入包含元组()的列表[]?

时间:2018-01-19 06:52:17

标签: python python-3.x dictionary

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

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

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

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

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

提前谢谢!

编辑:更改了标题

3 个答案:

答案 0 :(得分:1)

如果是元素列表:

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

答案 1 :(得分:1)

根据您发布的内容,我认为您有一个以换行符分隔的值的换行符分隔字符串。因此,首先我们将此字符串转换为制表符分隔值列表,然后将每个字符串转换为元组。

result = [tuple(line.split('\t')) for line in original.split('\n')]

答案 2 :(得分:0)

考虑string_given是您作为输入提供的字符串,output_string是您需要在以下代码中获得的输出...

可能有很多方法,但我使用了正常拆分和删除元素......如果我错了请告诉我

string_given= " 2012-01-01 09:00   San Jose    Men's Clothing  214.05  Amex"
output_string=list(string_given.strip().split())
output_string[2]=str.join(' ',(output_string[2],output_string[3]))
del output_string[3]
output_string[3]=str.join(' ',(output_string[3],output_string[4]))
del output_string[4]
print(output_string)

结果

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

将输出作为元组

tupled_string=tuple(output_string)
print([tupled_string])

结果是

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