Python程序:将数组列表转换为字符串,反之亦然


将列表转换为字符串

将列表转换为字符串的一种方法是遍历列表中的所有项目并将它们连接到一个空字符串中。

示例

lis=["I","want","cheese","cake"]
str=""
for i in lis:
    str=str+i
    str=str+" "
print(str)

输出

I want cheese cake 

使用join函数

join是Python中的一个内置函数,用于使用用户指定的间隔符连接可迭代对象(例如:列表)的项目。我们可以使用join函数将列表转换为字符串,但列表中的所有元素都应该是字符串,而不是其他类型。

如果列表包含任何其他数据类型的元素,则需要先使用str()函数将元素转换为字符串数据类型,然后才能使用join函数。

语法

join函数的语法如下:

S=” “.join(L)

其中,

  • S=连接后得到的字符串。

  • L=可迭代对象。

间隔符应在双引号内指定。

示例

lis=["I","want","cheese","cake"]
print("the list is ",lis)
str1=" ".join(lis)
str2="*".join(lis)
str3="@".join(lis)
print(str1)
print(str2)
print(str3)

输出

the list is  ['I', 'want', 'cheese', 'cake']
I want cheese cake
I*want*cheese*cake
I@want@cheese@cake

上面的示例给出了类型错误,因为列表中的所有项目都不是“字符串”类型。因此,为了获得正确的输出,列表项目2和3应该转换为字符串。

lis=["I",2,3,"want","cheese","cake"]
print("the list is ",lis)
str1=" ".join(str(i) for i in lis)
print("The string is ",str1)

输出

the list is  ['I', 2, 3, 'want', 'cheese', 'cake']
The string is  I 2 3 want cheese cake

将字符串转换为列表

可以使用split()函数将字符串转换为列表。split()函数将字符串作为输入,并根据提到的间隔符(间隔符是指字符串将被分割的字符)生成一个列表作为输出。如果未提及间隔符,则默认情况下空格将被视为间隔符。

语法

L=S.split()

其中,

  • S=要分割的字符串。

  • L=分割后得到的列表。

如果要使用除空格以外的任何其他间隔符,则必须在括号内用双引号将其提及。

Ex: L=S.split(“#”)

示例

以下是一个我们没有提及任何间隔符的示例:

s="let the matriarchy begin"
print("the string is:  ",s)
lis=s.split()
print("the list is: ",lis)

输出

以下是程序的输出。

the string is:   let the matriarchy begin
the list is:  ['let', 'the', 'matriarchy', 'begin']

使用间隔符“,”

s="My favourite dishes are Dosa, Burgers, ice creams,waffles"
print("the string is:  ",s)
lis=s.split(",")
print("the list is: ",lis)

输出

以下是程序的输出。

the string is:   My favourite dishes are Dosa, Burgers, ice creams,waffles
the list is:  ['My favourite dishes are Dosa', ' Burgers', ' ice creams', 'waffles']

使用间隔符“@”

s="Chrisevans@gmail.com"
print("the string is:  ",s)
lis=s.split("@")
print("the list is: ",lis)

输出

以下是程序的输出。

the string is:   Chrisevans@gmail.com
the list is:  ['Chrisevans', 'gmail.com']

更新于: 2023年4月24日

188 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.