Reputation: 110143
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
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
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
Reputation: 13410
', '.join('(' + ', '.join(i) + ')' for i in L)
Output:
'(Steve Buscemi, Mr. Pink), (Chris Penn, Nice Guy Eddie)'
Upvotes: 11
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