2013-04-21 72 views
-5

对于作业分配,我想实现一个函数numLen(),该函数使用字符串s和整数n作为参数,并返回长度为n的字符串s中的字数。字符串中的单词是由至少一个空格分隔的非空格字符。如何返回长度为n(python)的字符串s中的字数?

一个实例是将输入:

>>> numLen("This is a test", 4) 

和得到2,因为有2个字在字符串中具有4个字符。

我不知道如何做到这一点。

+0

行对自己的一个版本锻炼。查看split()方法和len()方法。 – ecline6 2013-04-21 19:35:48

+4

[你的同学?](http://stackoverflow.com/questions/16127550/how-do-i-find-the-number-of-times-a-word-is-of-len-n-in -python) – Cairnarvon 2013-04-21 19:36:09

+1

还有另一位同学http://stackoverflow.com/questions/16068312/counting-number-of-times-a-word-in-string-equals-a-length现在有没有人真的在做他们的功课?啧。 – ecline6 2013-04-21 19:49:39

回答

4

将字符串拆分为单词str.split(),迭代单词,将它们的长度与给定数字进行比较,返回计数。

下面是使用一些内建一个紧凑的实现:

In [1]: def numLen(s, n): 
    ...:  return sum(1 for w in s.split() if len(w) == n) 
    ...: 

In [2]: numLen("This is a test", 4) 
Out[2]: 2 

您可以通过构建沿这很容易在Python完成的

def numLen(s, n): 
    words = ... # build a list of separate words 
    i = 0 # a counter for words of length n 
    for word in words: 
     # check the length of 'word' 
     # increment the counter if needed 
    # return the counter 
+1

Pythonic .... +1 – Maroun 2013-04-21 19:35:40

+2

'sum(len(w)== n for s in s.split())'更小。 – 2013-04-21 19:36:40

+3

真的吗?我们做作业? – blue 2013-04-21 19:37:37

相关问题