将元组转换为字符串

时间:2015-03-14 13:43:35

标签: python regex

我想在python中将('nice', 'movement')转换为'nice movement'。 我认为元组的连接特征是不合适的,因为我想添加一个空格。

什么可能是正则表达式?

4 个答案:

答案 0 :(得分:2)

执行使用str.join() method,使用空格加入:

' '.join(yourtuple)

元组上没有join功能,您无法使用正则表达式连接序列。

演示:

>>> t = ('nice', 'movement')
>>> ' '.join(t)
'nice movement'

答案 1 :(得分:0)

如果你真的不想使用str.join,那么你可以functools.reduce

In [31]: import functools

In [32]: tup = ('nice', 'movement')

In [33]: functools.reduce(lambda x,y: x+" "+y, tup)
Out[33]: 'nice movement'

答案 2 :(得分:0)

你可以使用字符串的join属性(单个空格或任何你想要的分隔符)和任何迭代,如元组或字符串列表。

In [5]: ' '.join(('hello','world'))
Out[5]: 'hello world'

适用于Python 2和3(尝试过2.5和3.4)。

答案 3 :(得分:0)

根据您的具体情况,%运算符也可能适用:

t=("nice","movement")
print "%s %s" % t
相关问题