0

Say I have a string = "Nobody will give me pancakes anymore"

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

But when I want to know the length of 'Nobody' by inputing len(string[0]) it only gives me 1, because it thinks that the 0th element is just 'N' and not 'Nobody'.

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

3
  • 3
    So store the string.split() result in a new variable, and take the length of the first element of that. Commented Oct 15, 2016 at 21:54
  • @MartijnPieters I'm trying that but I get SyntaxError: can't assign to function call Commented Oct 15, 2016 at 21:56
  • sounds like you got the syntax for assigning wrong somewhere then. See my answer. Commented Oct 15, 2016 at 21:57

3 Answers 3

4

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])

Demo:

>>> string = "Nobody will give me pancakes anymore"
>>> words = string.split()
>>> words[0]
'Nobody'
>>> len(words[0])
6
Sign up to request clarification or add additional context in comments.

1 Comment

Oh I got it now! I didn't put the variable in order. Thank a lot!
1

Yup, string[0] is just 'N'

Regarding your statement...

I want to count each word in the string

>>> s = "Nobody will give me pancakes anymore"
>>> lens = map(lambda x: len(x), s.split())
>>> print lens
[6, 4, 4, 2, 8, 7]

So, then you can do lens[0]

Comments

0
words = s.split()   
d = {word : len(word) for word in words}

or

words = s.split()
d = {}

for word in words:
    if word not in d:
        d[word]=0
    d[word]+=len(word)

In [15]: d  
Out[15]: {'me': 2, 'anymore': 7, 'give': 4, 'pancakes': 8, 'Nobody': 6,   'will': 4}
In [16]: d['Nobody']
Out[16]: 6

2 Comments

So, d = {word : len(word) for word in words}? Why the defaultdict?
Thanks I was trying to write it in a more readable way. I have changed the answer thanks very much for the suggestion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.