Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Join List Elements with a String

Python Join List Elements with a String

Document Object Reference Manual Python3 Examples

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

print

(

result

)

Code analysis:

  1. my_list = ['Hello', 'World', 'Python']: Define a list containing three string elements.
  2. result = ' '.join(my_list): When using join() method joins the elements in the list into a single string,' ' indicating that a space is inserted as a separator between elements.
  3. print(result): Print the joined string.

Output result:

Hello World Python

Document Object Reference Manual Python3 Examples