Home >Backend Development >Python Tutorial >How to convert list to string in python
To convert a list into a string in python, first convert all the elements in the list into str type, and then use Python's built-in string function join to connect the elements in the list.
The examples are as follows:
>>> list1=['ak','uk',4] >>> list2=[str(i) for i in list1] #使用列表推导式把列表中的单个元素全部转化为str类型 >>> list2 #查看转化后的列表 ['ak', 'uk', '4'] >>> list3=' '.join(list2) #把列表中的元素放在空串中,元素间用空格隔开 >>> list3 #查看生成的长串 'ak uk 4'
Join function introduction:
The join() function in Python is used to connect the elements in the sequence with specified characters to generate a new String.
join() function syntax:
str.join(sequence)
Parameters: sequence -- the sequence of elements to be connected.
Return value: Returns a new string generated by concatenating elements in the sequence by the specified character.
The following examples show how to use join():
str = "-"; seq = ("a", "b", "c"); # 字符串序列 print str.join( seq );
The output results are as follows:
a-b-c
For more Python related technical articles, please visit Learn in the Python tutorial column!
The above is the detailed content of How to convert list to string in python. For more information, please follow other related articles on the PHP Chinese website!