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'
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'
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.
>>>
''.join(map(str, tup))
–
Hierocracy ''.join(map(lambda x: str(x or ''), (None, 1, 2, 'apple')))
–
Tamar here is an easy way to use join.
''.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'))
If just using str()
for a tuple as shown below:
t = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
print(t, type(t))
s = str(t) # Here
print(s, type(s))
Only the type can be changed from tuple
to str
without changing the value as shown below:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'tuple'>
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'str'>
© 2022 - 2024 — McMap. All rights reserved.
reduce(add, ('a', 'b', 'c', 'd'))
– Moonieradd
in this exmple @GrijeshChauhan? – Skilfuladd
function fromoperator
module. Btw"".join
better suits here but if you want to add different types of objects you can use add Check this working example – Moonier({'entities': [[44, 58, 'VESSEL'], [123, 139, 'VESSEL'], [146, 163, 'COMP'], [285, 292, 'ADDR'], [438, 449, 'ADDR'], [452, 459, 'ADDR']]},)
– Wax