📌  相关文章
📜  如何在Python中将列表转换为字符串

📅  最后修改于: 2020-10-28 01:46:43             🧑  作者: Mango

如何在Python中将列表转换为字符串?

可以使用以下方法将Python列表转换为字符串。让我们了解以下方法。

方法-1

给定的字符串使用for循环进行迭代,并将其元素添加到字符串变量中。

范例-

# List is converting into string
def convertList(list1):
    str = ''  # initializing the empty string

    for i in list1: #Iterating and adding the list element to the str variable
        str += i

    return str

list1 = ["Hello"," My", " Name is ","Devansh"] #passing string 
print(convertList(list1)) # Printin the converted string value

输出:

Hello My Name is Devansh

方法-2使用.join()方法

我们还可以使用.join()方法将列表转换为字符串。

示例-2

# List is converting into string
def convertList(list1):
    str = ''  # initializing the empty string

    return (str.join()) # return string

list1 = ["Hello"," My", " Name is ","Devansh"] #passing string
print(convertList(list1)) # Printin the converted string value

输出:

Hello My Name is Devansh

当列表同时包含字符串和整数作为元素时,不建议使用上述方法。在这种情况下,可以使用添加元素来对变量进行字符串。

方法-3

使用列表理解

# Converting list into string using list comprehension
list1 = ["Peter", 18, "John", 20, "Dhanuska",26]

convertList = ' '.join([str(e) for e in list1]) #List comprehension

print(convertList)

输出:

Peter 18 John 20 Dhanuska 26

方法-4

使用map()

# Converting list into string using list comprehension
list1 = ["Peter", 18, "John", 20, "Dhanuska",26]

convertList = ' '.join(map(str,list1)) # using map funtion

print(convertList)

输出:

Peter 18 John 20 Dhanuska 26