简体   繁体   中英

Have a list of tuples with strings, want to turn into a single string in Python

I have a data structure that looks like [("hello", 12), ("yo", 30)] . How do I combine all of the 0th position of each tuple into a string? The output of the above would be like: "helloyo" . Here is what I've tried:

' '.join[tuple[0] for tuple in tuples]

Nearly there, this will work:

''.join(t[0] for t in tuples)

BTW, don't use tuple as a variable, as it's also a python type.

How about:

d = [("hello", 12), ("yo", 30)]
' '.join( [ t[ 0 ] for t in d ] )

#output
'hello yo'

or if you don't want spaces:

d = [("hello", 12), ("yo", 30)]
''.join( [ t[ 0 ] for t in d ] )

#output
'helloyo'

What you've got almost works, except xxx.join joins the arguments with xxx as the separator, and since join is a function, it needs brackets around it.

So if you want 'helloyo' , just do:

''.join([tuple[0] for tuple in tuples])

In fact, for join , you don't even need the list comprehension:

''.join(tuple[0] for tuple in tuples)

您很亲密,但是join是一个函数,因此您需要(),而不是[]

join is a method if strings. You're using [] , you want ''.join() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM