Convert tuple to 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 to do

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

but encountered the following error:

 TypeError: sequence item 0: expected string, tuple found 

How would I do the above formatting?

+4
source share
5 answers
 ', '.join('(' + ', '.join(i) + ')' for i in L) 

Output:

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

You are close.

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

Output:

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

Destruction: the outer brackets are added separately, and the inner ones using the first '), ('.join . The list of names inside the parentheses is created using the separate ', '.join .

+5
source
 s = ', '.join( '(%s)'%(', '.join(item)) for item in items ) 
+3
source

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 strings. You can remove them with replace .

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

+1
source

you were close ...

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

or

 print str(items)[1:-1] 

or

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

Source: https://habr.com/ru/post/1434946/


All Articles