问题:Python将元组转换为字符串
我有一个这样的字符元组:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
我如何将其转换为字符串,使其类似于:
'abcdgxre'
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'
回答 0
用途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.
>>>
Use 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.
>>>
回答 1
这是使用联接的一种简单方法。
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
here is an easy way to use join.
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
回答 2
这有效:
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
它将生成:
'abcdgxre'
您还可以使用定界符(例如逗号)来生成:
'a,b,c,d,g,x,r,e'
通过使用:
','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
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'))
回答 3
最简单的方法是像这样使用join:
>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'
之所以有效,是因为您的定界符实际上什么都没有,甚至没有空格:”。
Easiest way would be to use join like this:
>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'
This works because your delimiter is essentially nothing, not even a blank space: ”.