'Python join string elements in separate lists then add lists together
If I have two lists of individual string characters:
['H', 'e', 'l', 'l', 'o']
['w', 'o', 'r', 'l', 'd']
How do I make the final outcome look like this below of one list and where all of the string characters are combined:
['Hello','world']
If I try something like this:
word1join = "".join(word1)
word2join = "".join(word2)
print(word1join,type(word1join))
print(word2join,type(word1join))
print(list(word1join + word2join))
I am recreating the original data structure again but incorrectly, any tips appreciated!
Hello <class 'str'>
world <class 'str'>
['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
Solution 1:[1]
Just create a new list with them in:
word1 = ['H', 'e', 'l', 'l', 'o']
word2 = ['w', 'o', 'r', 'l', 'd']
word1join = "".join(word1)
word2join = "".join(word2)
print([word1join, word2join])
Output as requested
Solution 2:[2]
If your variable names have numbers in them, it's usually a good hint that you should better be manipulating one list, rather than several individual variables.
Instead of starting with two variables:
word1 = ['H', 'e', 'l', 'l', 'o']
word2 = ['w', 'o', 'r', 'l', 'd']
Start with one list:
words = [['H', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
You can still access individual words using indexing:
print(words[1])
# ['H', 'e', 'l', 'l', 'o']
You can then apply operations to every element of that list using for-loops, or list comprehensions, or function map:
words_joined = [''.join(word) for word in words]
# ['Hello', 'world']
# OR ALTERNATIVELY
words_joined = list(map(''.join, words))
# ['Hello', 'world']
If you really need to split the list into two variables, you can still do it:
word1joined, word2joined = words_joined
print(word2joined)
# world
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | quamrana |
| Solution 2 | Stef |
