Home > Backend Development > Python Tutorial > How to convert list to string in python

How to convert list to string in python

Release: 2019-07-08 09:07:12
Original
20122 people have browsed it

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'
Copy after login

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 );
Copy after login

The output results are as follows:

a-b-c
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template