Reputation: 33
I have list of lists consisting of chars and integers like this:
list = [[65], [119, 'e', 's', 'i'], [111, 'd', 'l'], [111, 'l', 'w'], [108, 'd', 'v', 'e', 'i'], [105, 'n'], [97, 'n'], ['111', 'k', 'a']]
I want to convert this into a single string like this:
"65 119esi 111dl 111lw 108dvei 105n 97n 111ka"
I have tried this:
new_list = [' '.join(x for x in list)]
but it is giving me this error:
TypeError: sequence item 0: expected str instance, list found
So what am i supposed to do, I'm new to coding!
Upvotes: 2
Views: 1792
Reputation: 73460
You have ints in your sublists aswell, that need converting before joining. You can do the following, using map
to do the string conversion of the tokens and str.join
to piece them together:
lst = [[65], [119, 'e', ... ] # do NOT call a variable "list"
new_lst = " ".join("".join(map(str, sub)) for sub in lst)
# '65 119esi 111dl 111lw 108dvei 105n 97n 111ka'
Upvotes: 0
Reputation: 315
To make it a bit easier to see what is happening you could use:
final_string = ""
for elem in list:
final_string = final_string + " "
for el in elem:
final_string = final_string +str(el)
Upvotes: 0
Reputation: 982
That error you get is because .join() expects strings to join together, but you are passing it a list instead (one of the subarrays).
A one liner would be:
" ".join(["".join([str(item) for item in sublist]) for sublist in your_list])
Note that this only works for one level of nested arrays. If you had more or indefinite, probably its better to write your own function that does the job.
Upvotes: 2