domiziano
domiziano

Reputation: 470

How to put together all the words in a string?

Using a loop, how can I convert a string in a unique term, where all the words are linked together with '_'?

starting from this:

[['Drama'],
 ['Drama', 'Horror', 'Thriller'],
 ['Drama'],
 ['Children', 'Drama'],
 ['Comedy', 'Drama', 'Horror', 'Thriller']

I would obtain this:

[['Drama'],
 ['Drama_Horror_Thriller'],
 ['Drama'],
 ['Children_Drama'],
 ['Comedy_Drama_Horror_Thriller']

Upvotes: 2

Views: 112

Answers (2)

A.B
A.B

Reputation: 20445

You can use map as well, joining every element with _ using lambda function.

l = [['Drama'],
 ['Drama', 'Horror', 'Thriller'],
 ['Drama'],
 ['Children', 'Drama'],
 ['Comedy', 'Drama', 'Horror', 'Thriller']]

# map() to join each member with `_`
#if you want it in form [[],[],[]]
test =  list(map(lambda x: ['_'.join(x)] , l)) 
#or if in list ['','','']
#test = list(map(lambda x: '_'.join(x) , l)) 
print(test) 

Upvotes: 1

Arty
Arty

Reputation: 16737

inp = (
[['Drama'],
 ['Drama', 'Horror', 'Thriller'],
 ['Drama'],
 ['Children', 'Drama'],
 ['Comedy', 'Drama', 'Horror', 'Thriller']]
)

print([['_'.join(l)] for l in inp])

Upvotes: 3

Related Questions