Kostas Petrakis
Kostas Petrakis

Reputation: 93

How can I sum a list of string objects in Python?

I want to make a function that takes a list which contains some words and prints only the first letter of each word in order to make one new word.

So my function is right here:

def word(x):
    li = []
    for w in x:
        li.append(w[0])
    return sum(li)


But unfortunately, it gives me the following error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Can you please explain me why is this happening ?

Upvotes: 1

Views: 24775

Answers (1)

Setop
Setop

Reputation: 2490

assuming words are separated by space,

S="this is my sentense"

"".join(map(lambda x: x[0], S.split(" ")))

returns

'tims'

explanation :

  • split in words using space
  • for each word ("map" function), take first character (x[0])
  • then join the result using void

Upvotes: 2

Related Questions