Python 列表可以通過以下方法轉換為字元串。讓我們了解以下方法。
給定的字元串使用 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
我們也可以使用。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
當列表同時包含字元串和整數作為其元素時,不建議使用上述方法。在這種情況下,請使用將元素添加到字元串變數。
使用列表推導
# 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
使用地圖()
# 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
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126692.html