Python pure number list converted to string problem

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, and dictionary type data into strings.
Usage syntax: 'sep'.join(seq)
parameter description:
sep: specifies the separator, which can be empty.
seq: The sequence of elements to be connected, which can be a list, tuple, or dictionary.
Return value: a new string composed of specified delimiters

Convert list to string (python3)
Example 1: List elements are all string data types

# 将元素全为字符串数据类型的列表转换成字符串
a = ['1', '2', '3', 'abc', 'def']
print('结果:', ''.join(a))

Result: 123abcdef

Example 2: Numeric type data exists in the list element.
Insert image description here
Insert image description here
Problem: When numeric type data exists in the list element, an error is reported!
Reason: When using the join() function to combine list type data, all elements in the list need to be of string type.
Solution to the above error: Just ensure that all elements in the list are converted into strings. Therefore
, the above error code can be changed to:

# 列表元素存在数字类型数据,正确写法
b = [1, 2, 3]
b = [str(i) for i in b]
b1 = [1, 2, 3, 'a']
b1 = [str(i) for i in b1]
print('b结果:', ''.join(b))
print('b1结果:', ''.join(b1))

b result: 123
b1 result: 123a

—end—

Guess you like

Origin blog.csdn.net/LHJCSDNYL/article/details/122400435
Recommended