[英]Python convert tuple to string
我有一个这样的字符元组:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
如何将其转换为字符串,使其类似于:
'abcdgxre'
使用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.
>>>
这是一种使用join的简单方法。
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
这有效:
''.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'))
最简单的方法是使用这样的连接:
>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'
这是有效的,因为你的分隔符基本上没有,甚至不是空格:''。
如果只是将str()
用于元组,如下所示:
t = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
print(t, type(t))
s = str(t) # Here
print(s, type(s))
只有类型可以从tuple
更改为str
而无需更改值,如下所示:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'tuple'>
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'str'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.