Python将元组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19641579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python convert tuple to string
提问by intel3
I have a tuple of characters like such:
我有一个像这样的字符元组:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
How do I convert it to a string so that it is like:
如何将其转换为字符串,使其类似于:
'abcdgxre'
采纳答案by intel3
Use str.join
:
使用str.join
:
>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:
join(...)
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>>
回答by Back2Basics
here is an easy way to use join.
这是使用 join 的简单方法。
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
回答by TruthSeeker
This works:
这有效:
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
It will produce:
它将产生:
'abcdgxre'
You can also use a delimiter like a comma to produce:
您还可以使用逗号等分隔符来生成:
'a,b,c,d,g,x,r,e'
By using:
通过使用:
','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
回答by W_water_m
Easiest way would be to use join like this:
最简单的方法是像这样使用 join:
>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'
This works because your delimiter is essentially nothing, not even a blank space: ''.
这是有效的,因为您的分隔符基本上什么都没有,甚至不是空格:''。