面试题---统计一个字符串里面的单词个数

1、统计一个字符串里面的单词个数

 

2、统计单词个数

 1 s = "Today is sunny! Yes, you are right!"
 2 new_s = ""
 3 for i in s:
 4     # 如果i是空格或者大小写字母,则直接保存到new_s中
 5     if i ==" " or ("a" <= i <="z") or ("A" <= i <="Z"):
 6         new_s += i
 7     # 如果i是其他,则替换为空格
 8     else:
 9         new_s += " "
10 
11 print(new_s)
12 print(new_s.split())
13 print(len(new_s.split()))

运行结果如下:

posted @ 2020-06-23 16:37  anna1210  阅读(345)  评论(0编辑  收藏  举报