David542
David542

Reputation: 110143

Tuple conversion to a string

I have the following list:

[('Steve Buscemi', 'Mr. Pink'), ('Chris Penn', 'Nice Guy Eddie'), ...]

I need to convert it to a string in the following format:

"(Steve Buscemi, Mr. Pink), (Chris Penn, Nice Guy Eddit), ..."

I tried doing

str = ', '.join(item for item in items)

but run into the following error:

TypeError: sequence item 0: expected string, tuple found

How would I do the above formatting?

Upvotes: 4

Views: 2399

Answers (5)

Mark Ransom
Mark Ransom

Reputation: 308140

You're close.

str = '(' + '), ('.join(', '.join(names) for names in items) + ')'

Output:

'(Steve Buscemi, Mr. Pink), (Chris Penn, Nice Guy Eddie)'

Breaking it down: The outer parentheses are added separately, while the inner ones are generated by the first '), ('.join. The list of names inside the parentheses are created with a separate ', '.join.

Upvotes: 5

Zenon
Zenon

Reputation: 1509

You can simply use:

print str(items)[1:-1].replace("'", '') #Removes all apostrophes in the string

You want to omit the first and last characters which are the square brackets of your list. As mentioned in many comments, this leaves single quotes around the strings. You can remove them with a replace.

NB As noted by @ovgolovin this will remove all apostrophes, even those in the names.

Upvotes: 1

mgilson
mgilson

Reputation: 309891

s = ', '.join( '(%s)'%(', '.join(item)) for item in items )

Upvotes: 3

ovgolovin
ovgolovin

Reputation: 13410

', '.join('(' + ', '.join(i) + ')' for i in L)

Output:

'(Steve Buscemi, Mr. Pink), (Chris Penn, Nice Guy Eddie)'

Upvotes: 11

Joran Beasley
Joran Beasley

Reputation: 113948

you were close...

print ",".join(str(i) for i in items)

or

print str(items)[1:-1]

or

print ",".join(map(str,items))

Upvotes: 0

Related Questions