Python Join List Elements with a String
In Python, we can use join() method to join the string elements in a list.join() method joins all string elements in the list into a single string, and can insert a specified separator between elements.
Example
Define a list containing strings
my_list
=
[
'Hello'
,
'World'
,
'Python'
]
Use the join() method to join the elements in the list, using a space as the separator
result
=
' '
.
join
(
my_list
)
Print the result
(
result
)
Code analysis:
my_list = ['Hello', 'World', 'Python']: Define a list containing three string elements.result = ' '.join(my_list): When usingjoin()method joins the elements in the list into a single string,' 'indicating that a space is inserted as a separator between elements.print(result): Print the joined string.
Output result:
Hello World Python
Python3 Examples