Skip to content Skip to sidebar Skip to footer

Python - Is It Possible To Convert A String And Put It Into A List [] Containing Tuple ()?

For example, these two are the strings and they are separated by tabs. 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex Is it possible to convert string to list [] conta

Solution 1:

If it is a list of elements:

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

Result:

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

or if it is a list of tuple:

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

Result:

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

And if you have multiple line of the string:

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

Result:

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

Solution 2:

From what you posted, I suppose you have a newline-separated string of tab-separated values. Hence, first we translate this string into a list of tab-separated values, and then translate each into tuples.

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

Solution 3:

consider the string_given is the string you are giving as input and output_string is the output u need to get in the following piece of code...

there may be a tons of methods but i have used normal splitting and deleting the elements...please let me know if i am wrong

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)

Result

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

for making the output as tuple

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

Result is

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

Post a Comment for "Python - Is It Possible To Convert A String And Put It Into A List [] Containing Tuple ()?"