2013-12-15 40 views
0

我在做什么,现在正在计数的空格数,再加入1
但如果用户输入类似"heres a big space______amazing right?"
程序会计算所有的6位和比方说,有10个字时实际上它是6计数字符串中的单词的数量

phrase = raw_input("Enter a phrase: ") 
space_total = 0 
for ch in phrase: 
    if ch == " ": 
     space_total += 1 
words = space_total + 1 
print "there are", words, "in the sentence" 

回答

3

使用str.split()分裂上的空白的线,然后使用结果的长度:

len(phrase.split()) 

str.split()不带参数,或None作为第一个参数,将分割为任意宽度 whitespace;不管有多少个空格或制表符,换行符词与词之间的使用,它会分解产生只是单词列表(其中一个词是什么,是不是空白):

>>> 'Hello world! This\tis\t   awesome!'.split() 
['Hello', 'world!', 'This', 'is', 'awesome!'] 
>>> len('Hello world! This\tis\t   awesome!'.split()) 
5 
+0

好的,它工作。非常感谢!! –

0
>>> import re 
>>> s = "test test1 test2 abc" 
>>> re.findall("\w+", s) 
['test', 'test1', 'test2', 'abc'] 
>>> ret = re.findall("\w+", s) 
>>> len(ret) 
4 
+0

通常're'要慢得多,所以我们尽量避免它,除非必要。 – Ray

+0

@Ray是的,你是对的 – henices

相关问题