首页 > 编程知识 正文

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

时间:2023-11-25 15:30:09 阅读:309145 作者:YCNO

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

使用地图()


# 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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。