Shankar Pandey
Shankar Pandey

Reputation: 451

Join String with a List of Tuples

Need help with concatenating a String Object with a List of Tuples :

Input :

My_String = 'ABC | DEF | GHI'
My_List = [('D1', 2.0), ('D2', 3.0)]

Output expected :

'ABC | DEF | GHI | D1 | 2.0'
'ABC | DEF | GHI | D2 | 3.0'

I tried concatenating, but its doing a cross product with the elements in the tuple and is coming as follows :

[
['ABC | DEF | GHI|D1'
'ABC | DEF | GHI | 2.0']
['ABC | DEF | GHI|D2'
'ABC | DEF | GHI | 3.0']
]

Upvotes: 2

Views: 2063

Answers (4)

kezzos
kezzos

Reputation: 3221

Using a combination of format, and tuple unpacking:

print map(lambda x: "{} | {} | {}".format(My_String, *x), My_List)

Upvotes: 0

Dunny
Dunny

Reputation: 170

For the string and tuple you have, the following is a simple and easy to follow way of solving your problem

the_string = "ABC | DEF | GHI"
the_list = [('D1', 2.0), ('D2', 3.0)]
#you need to loop through the tuple to get access to the values in the tuple
for i in the_list:
    print the_string, " | "+ str(i[0])+" | "+ str(i[1])

Upvotes: 1

Farhan.K
Farhan.K

Reputation: 3485

You can use a template and then use format:

My_String = 'ABC | DEF | GHI'
My_List = [('D1', 2.0), ('D2', 3.0)]

template = My_String + ' | {} | {}'

for i,j in My_List:
    print(template.format(i,j))

Output:

ABC | DEF | GHI | D1 | 2.0
ABC | DEF | GHI | D2 | 3.0

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249123

Try this:

for name, value in My_List:
    print(' | '.join((My_String, name, str(value))))

Upvotes: 4

Related Questions