Stefan Stefan - 1 year ago 85
Python Question

Counting sub-element in string?

Say I have a

string = "Nobody will give me pancakes anymore"

I want to count each word in the string. So I do
to get a list in order to get
['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore']

But when I want to know the length of
by inputing
it only gives me
, because it thinks that the 0th element is just
and not

What do I have to do to ensure I can find the length of the whole word, rather than that single element?

Answer Source

You took the first letter of string[0], ignoring the result of the string.split() call.

Store the split result; that's a list with individual words:

words = string.split()
first_worth_length = len(words[0])


>>> string = "Nobody will give me pancakes anymore"
>>> words = string.split()
>>> words[0]
>>> len(words[0])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download