Ben
Ben

Reputation: 11

Trying to concatenate strings and add integers to a sum separately

I posted this earlier and trying to figure out if this works better in terms of presentation. I am trying to concatenate strings and sum the integers from a list separately. For some reason, I am not getting the output I expected

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

Upvotes: 0

Views: 58

Answers (3)

Ramineni Ravi Teja
Ramineni Ravi Teja

Reputation: 3906

use isinstance function instead of type. Tested code here:

l = ['magical unicorns', 19, 'hello', 98.98, 'world']
con=''
sum=0
for i in l:
    print (i)
    if isinstance(i, str):
       con = con+str(i)
    elif isinstance(i, int):
       sum = sum+i
    else:
       pass
print (con)
print (sum)

Upvotes: 0

chx3
chx3

Reputation: 238

For concatenating strings:

print "".join(filter(lambda x: isinstance(x, basestring), l))

Output:

'magical unicornshelloworld'

For sum the integers:

import numbers
print sum(filter(lambda x: isinstance(x, numbers.Number), l))

Output:

117.98

Upvotes: 0

John Anderson
John Anderson

Reputation: 38892

"type(i) is 'str'" will never be True. Try something like isinstance(i, str) instead. Similar for the int check. Actually, type(i) is str will also work. Note that str is not in quotes.

Upvotes: 3

Related Questions