编写一个 Python示例,将元组转换为字符串。我们使用 Python 字符串连接函数来连接或转换元组项。
# Tuple To String
strTuple = ('p', 'y', 't', 'h', 'o', 'n')
print("Tuple Items = ", strTuple)
stringVal = ''.join(strTuple)
print("String from Tuple = ", stringVal)
Tuple Items = ('p', 'y', 't', 'h', 'o', 'n')
String from Tuple = python
在这个 Python Tuple to String 示例中,我们使用 for 循环(对于 strTuple 中的 t)和 for 循环范围(对于 range(len(strTuple))来迭代元组项。在循环中,我们将每个元组项连接到声明的字符串。
# Tuple To String
strTuple = ('t', 'u', 't', 'o', 'r', 'i', 'a', 'l')
print("Tuple Items = ", strTuple)
strVal = ''
for t in strTuple:
strVal = strVal + t
print("String from Tuple = ", strVal)
stringVal = ''
for i in range(len(strTuple)):
stringVal = stringVal + strTuple[i]
print("String from Tuple = ", stringVal)
Tuple Items = ('t', 'u', 't', 'o', 'r', 'i', 'a', 'l')
String from Tuple = tutorial
String from Tuple = tutorial
这个 Python 示例使用 lambda 函数将元组项转换为字符串。
# Tuple To String
from functools import reduce
strTuple = ('t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's')
print("Tuple Items = ", strTuple)
strVal = reduce(lambda x, y: str(x) + str(y), strTuple, '')
print("String from Tuple = ", strVal)
标签: 手机支付