简体   繁体   中英

Python from tuples to strings

new to the python programming, havin some difficulties figuring this out. I'm trying to convert tuples into strings, for example ('h','e',4) into 'he4'. i've submitted a version using the .join function, and i'm required to come up with another ver. i'm given the following:

def filter(pred, seq): # keeps elements that satisfy predicate
    if seq == ():
        return ()
    elif pred(seq[0]):
        return (seq[0],) + filter(pred, seq[1:])
    else:
        return filter(pred, seq[1:])

def accumulate(fn, initial, seq):
    if seq == ():
        return initial
    else:
        return fn(seq[0],  accumulate(fn, initial, seq[1:]))

hints on how to use the following to come up with conversion of 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'

Just loop through the tuple.

#tup stores your tuple
string = ''
for s in tuple :
    string+=s

Here you are going through the tuple and adding each element of it into a new string.

1) Use reduce function:

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

2) Use foolish recursion:

>>> def str_by_recursion(t,s=''):
        if not t: return ''
        return str(t[0]) + str_by_recursion(t[1:])

>>> str_by_recursion(t)
'he4'

You can use map to and join.

tup = ('h','e',4)
map_str = map(str, tup)
print(''.join(map_str))

Map takes two arguments. First argument is the function which has to be used for each element of the list. Second argument is the iterable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM