问题描述
计算字符串中的单词数,其中一个单词定义为不含空格的连续字符串。
示例
输入 "Hello, my name is finthon" ,输出为 5 。
代码实现
方法一
1 2 3 4 5 6 7 8 9 10 11 |
def count_words(str): # 计算单词数 num = 0 for i in range(len(str)): if str[i] != ' ' and (i == 0 or str[i-1] == ' '): num += 1 return num s = "Hello, my name is finthon" print("输入:", s) print("输出:", count_words(s)) |
方法二
1 2 3 4 |
s = "Hello, my name is finthon" num = len(s.strip().split(' ')) print("输入:", s) print("输出:", num) |
运行结果
1 2 |
输入:Hello, my name is finthon 输出:5 |