Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append list of numerous types to single string (python)

If I have a list as such:

arr = [
         ["Hi ", "My ", "Name "],
         ["Is ", "Sally. ", "Born "],
         [3, 13, 2010]  
]

How would you get that in a single string that states

H, My Name Is Sally. Born 3 13 2010

Is there a simpler way than

example = ""
for x in range(len(arr)): 
    for j in range(len(arr[x])):
        example = example + str(arr[x][j])
print (example) 
like image 917
William Merritt Avatar asked Feb 27 '18 19:02

William Merritt


People also ask

How do I merge a list of strings into one string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I combine a list of strings into a single string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do you append multiple lists in Python?

Using + operator to append multiple lists at once This can be easily done using the plus operator as it does the element addition at the back of the list. Similar logic is extended in the case of multiple lists.

Can you append a list to a string in Python?

Using join() to append strings in Python We create a list and the strings are appended to the list and then using the join() function we merge them into a single string.


1 Answers

You can use ' '.join:

myList = [
     ["Hi ", "My ", "Name "],
     ["Is ", "Sally. ", "Born "],
     [3, 13, 2010]  
] 

sentence = ''.join(str(i)+[' ', ''][type(i) == str] for b in myList for i in b)[:-1]

Output:

'Hi My Name Is Sally. Born 3 13 2010'
like image 191
Ajax1234 Avatar answered Nov 15 '22 05:11

Ajax1234