简体   繁体   中英

for loop to concatenate strings

I need to concatenate strings in the list and add the integers to a sum; of course, I intend to change it to other data types later - thanks so much for all your kind responses

l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int

I am just getting the '0' output that was initialized in the beginning as if it skipped over the for loop :)

Taking your statements literally (that you only want integers, not numerics) the entire program comes down to two function calls with filtered versions of the list

>>> l = ['magical unicorns', 19, 'hello', 98.98, 'world']
>>> ''.join([s for s in l if isinstance(s,str)])
'magical unicornshelloworld'
>>> sum([i for i in l if isinstance(i,int)])
19
>>
for i in l:
   if type(o) is str:
      comb_str += i
   else:
      comb_int += i

Note that comb_int appears to be a bit of a misnomer, since non-integer values in the list are being added to it. Perhaps these are supposed to be cast to int first?

Also note that this code will fail for a non-String/integer/double object in the list, so watch for exceptions.

Finally, be aware that the string joining is relatively slow ( O(n) time-wise) ), so take a look at Str.join as a better solution.

You can try this out:

l = ['magical unicorns', 19, 'hello', 98.98, 'world']
l1 = [g for g in l if type(g)==int]
l2 = [g for g in l if type(g)==str]
print(sum(l1))
print(''.join(l2))

This will print your desired outcome.

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