首页 > 编程知识 正文

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

时间:2023-11-25 09:12:55 阅读:309037 作者:QNZO

编写一个 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

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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。