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)
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.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With