freeCodeCamp/guide/english/python/string-methods/string-join-method/index.md

1.2 KiB

title
String Join Method

String Join Method

The str.join(iterable) method is used to join all elements in an iterable with a specified string str. If the iterable contains any non-string values, it raises a TypeError exception.

iterable: All iterables of string. Could a list of strings, tuple of string or even a plain string.

Examples

  1. Join a ist of strings with ":"
print ":".join(["freeCodeCamp", "is", "fun"])

Output

freeCodeCamp:is:fun
  1. Join a tuple of strings with " and "
print " and ".join(["A", "B", "C"])

Output

A and B and C
  1. Insert a " " after every character in a string
print " ".join("freeCodeCamp")

Output:

f r e e C o d e C a m p
  1. Joining with empty string.
list1 = ['p','r','o','g','r','a','m']  
print("".join(list1))

Output:

program
  1. Joining with sets.
test =  {'2', '1', '3'}
s = ', '
print(s.join(test))

Output:

2, 3, 1

More Information:

Python Documentation on String Join