当前分类:300例题>>正文

Python示例:将列表转换为字符串

来源:互联网   更新时间:2023年6月28日  

Python 示例

写一个 Python示例把列表转换成字符串。在 Python 中,我们可以使用字符串连接方法将列表连接或转换为字符串。

strlist = ["Kiwi", "USA", "UK", "India", "Japan"]

str1 = ' '
str1 = str1.join(strlist)
print(str1)

使用列表理解将列表转换为字符串的 Python示例。

strlist = ["Learn", "Python", "From", "Tutorial", "Gateway"]

str1 = ' '.join([str(word) for word in strlist])
print(str1)
Learn Python From Tutorial Gateway

Python示例使用字符串连接和映射功能将列表转换为字符串。

strlist = ["Learn", "Python", "From", "Tutorial", "Gateway"]

str1 = ' '.join(map(str, strlist))
print(str1)
Learn Python From Tutorial Gateway

在这个 Python 将列表转换为字符串示例中,for in 循环迭代列表项,并将它们添加到空字符串中。

def listToString(strlist):
    str1 = ''

    for word in strlist:
        str1 = str1 + word + ' ' 

    return str1

strlist = ["Python", "Programs", "From", "Tutorial", "Gateway"]

print(listToString(strlist))
Python Programs From Tutorial Gateway 

在这个 Python 示例中,我们展示了将列表转换为字符串的所有可能性。

def listToString(strlist):
    str1 = ''

    for word in strlist:
        str1 = str1 + word + ' ' 

    return str1

strlist = ["Learn", "Python", "Program", "From", "Tutorial", "Gateway"]

str1 = ' '
str1 = str1.join(strlist)
print("join method output        = ", str1)

str2 = ' '.join([str(word) for word in strlist])
print("List Comprehension output = ", str2)

str3 = ' '.join(map(str, strlist))
print("map output                = ", str3)

print("Custom Function output    = ", listToString(strlist))
join method output        =  Learn Python Programs From Tutorial Gateway
List Comprehension output =  Learn Python Programs From Tutorial Gateway
map output                =  Learn Python Programs From Tutorial Gateway
Custom Function output    =  Learn Python Programs From Tutorial Gateway 
本文固定链接:https://6yhj.com/leku-p-4516.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 域名备案