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.