寫一個 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://www.506064.com/zh-hk/n/287226.html