'How can I join strings within a list in Python? [closed]
I have the following list:
values = ['A', 'C', 'B', 'D']
Is there a way I can get it to output the list as the following string?
result = 'AC BD'
Solution 1:[1]
list = ['A', 'C', 'B', 'D']
a=''.join(list[0:2])
b=''.join(list[2:4])
print(f'{a} {b}')
# AC BD
Solution 2:[2]
In one line:
''.join(list[0:2]) + ' ' + ''.join(list[2:4])
Solution 3:[3]
Using the zip
function and list comprehension will get you there:
[''.join(i) for i in zip(l[::2], l[1::2])]
Output:
['AC', 'BD']
Where l
is the list.
An advantage, is this approach will work for a larger list as well.
To make a simple string, just use this around the whole statement, or the result:
' '.join(result)
>>> 'AC BD’
Solution 4:[4]
If you want to concatenate items in a list then you can run the join command, where between the brackets you can specify the join character (e.g. empty, a space or a comma).
This should do the trick:
''.join(list)
# returns: ACBD
If you want to have a space in between AC and BD then the other answers are correct and you can join subsets of the list into a single string. For example as provided by Maciej.
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 | DevScheffer |
Solution 2 | Peter Mortensen |
Solution 3 | |
Solution 4 | Peter Mortensen |