Python 程序将元组转换为字符串

编写一个 Python 程序将元组转换为字符串。在下面的示例中,我们使用字符串 join 函数来连接或转换元组项。

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 程序使用 for 循环将元组转换为字符串

在此元组到字符串的示例中,我们使用 for 循环 (for t in strTuple) 和 for 循环范围 (for i in range(len(strTuple))) 来迭代元组项。在循环中,我们将每个元组项连接到一个声明的字符串。

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

此示例使用 lambda 函数 和 str() 函数将元组项转换为字符串。

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)
Convert Tuple To String