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

发布时间:2022-07-24

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