tup1 = ("h", "e", "l", "l", "o")
# Use str.join() to convert tuple to string.
str = "".join(tup1)
print(str)
分隔符(如逗号)也可以添加到转换后的字符串中。以下代码使用带有分隔符 ,
的 str.join()
方法将元组转换为字符串。
tup1 = ("h", "e", "l", "l", "o")
# Use str.join() to convert tuple to string.
str = ",".join(tup1)
print(str)
在 Python 中使用 reduce()
函数将元组转换为字符串
reduce(fun, seq)
函数用于应用在传递的序列中引用的整个列表组件中传递的特定函数。
在这种方法中,我们需要导入 functools
和 operator
模块以成功运行代码。
functools
模块提供了使高阶函数可以在其他函数上工作的功能。
以下代码使用 reduce()
函数将元组转换为字符串。
import functools
import operator
tup1 = ("h", "e", "l", "l", "o")
# Use reduce() to convert tuple to string.
str = functools.reduce(operator.add, (tup1))
print(str)
在 Python 中使用 for
循环将元组转换为字符串
一个基本的 for
循环也可以用于遍历元组中的所有元素,然后将这些元素附加到字符串中。
我们使用一个元组和一个空字符串。元组的所有元素都被迭代以附加到空字符串中。
以下代码使用 for
循环在 Python 中将元组转换为字符串。
tup1 = ("h", "e", "l", "l", "o")
str = ""
# Use for loop to convert tuple to string.
for item in tup1:
str = str + item
print(str)
hello
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
LinkedIn