The join() function in Python is used to combine all elements in a sequence into a new string according to the specified delimiter.
Commonly used to convert list, tuple, dictionary type data into strings
Use syntax: 'sep'.join(seq)
Parameter description:
sep: specify the separator, can be empty.
seq: The sequence of elements to be connected, which can be a list, a tuple, or a dictionary.
Return value: a new string composed of the specified delimiters
Convert list to string (python3)
Example 1: List elements are all string data types
# Convert a list whose elements are all string data types to stringsa = ['1', '2', '3', 'abc', 'def']print('results:', ''.join(a))
Result: 123abcdef
Example 2: Number type data exists in the list element
Problem: When there is numeric type data in the list element,Error!
Reason: When using the join() function to combine list type data, all the elements in the list need to be of string type.
The solution to the above error: ensure that all the elements in the list are converted into strings
Therefore, the above error code can be changed to:
# There is numeric type data in the list element, the correct spellingb = [1, 2, 3]b = [str(i) for i in b]b1 = [1, 2, 3, 'a']b1 = [str(i) for i in b1]print('bresults:', ''.join(b))print('b1 result:', ''.join(b1))
b result: 123
b1 result: 123a
—end—