我有一个字符元组,形式如下:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
我该如何将它转换为字符串,使其变成这样:
'abcdgxre'
我有一个字符元组,形式如下:
('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(map(str, tup))
。 - Mo Beigi''.join(map(lambda x: str(x or ''), (None, 1, 2, 'apple')))
. - xjlin0这里有一个使用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'))
如果只是像下面这样对元组使用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'>
>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'
这个代码能够运行是因为你的分隔符实际上是空的,甚至没有一个空格:''。
reduce(add, ('a', 'b', 'c', 'd'))
- Grijesh Chauhanadd
是什么? - Steveoperator
模块导入add
函数。顺便说一下,"".join
更适合这里,但如果你想添加不同类型的对象,可以使用 add。请查看这个工作示例。 - Grijesh Chauhan({'entities': [[44, 58, 'VESSEL'], [123, 139, 'VESSEL'], [146, 163, 'COMP'], [285, 292, 'ADDR'], [438, 449, 'ADDR'], [452, 459, 'ADDR']]},)
- Pravin