Python Convert Tuple to String

Python convert tuple to string

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.

>>>

Python from tuples to strings

The given filter is useless for this but the given accumulate can be used easily:

>>> t = ('h','e',4)
>>> accumulate(lambda x, s: str(x) + s, '', t)
'he4'

Python: Converting from Tuple to String?

This also works:

>>> s = "Tuple: " + str(tup)
>>> s
"Tuple: (2, 'a', 5)"

How to convert data type for list of tuples string to float

you have a problem in your code because the x that you are using is a tuple. The elements of the list you provided are tuples type (String,String) so you need one more iteration on the elemts of the tuples. I have modified your code to :

newresult = []
for tuple in result:
temp = []
for x in tuple:
if x.isalpha():
temp.append(x)
elif x.isdigit():
temp.append(int(x))
else:
temp.append(float(x))
newresult.append((temp[0],temp[1]))
print(newresult)

I have tested the code :

 //input 
result= [('Books', '10.000'),('Pen', '10'),('test', 'a')]
//output
[('Books', 10.0), ('Pen', 10), ('test', 'a')]


Related Topics



Leave a reply



Submit