python中打印一个字符串中有多少个单词

1.for实现:

str1 = str.strip(input("please input a str:"))
n = 1
i = 0
for i in range(len(str1)-1):
if str.isalnum(str1[i]) != str.isalnum(str1[i+1]):
n += 1
else:
i += 1
print("字符个数为:",int((n+1)/2))

2.while实现:
# str1 = str.strip(input("please input a str:"))
# n = 0
# i = 0
# while i < len(str1):
# while str1[i] != " ":
# i += 1
# if i == len(str1):
# break
# n += 1
# if i == len(str1):
# break
# while str1[i] == " ":
# i += 1
# print(n)




+++++++++++++++++++++++++++++++++++++++++++++++++++++

# str1 = str.strip(input("please input a str:"))
# n = 1
# i = 0
# while i < len(str1):
# while str1[i] == ' ':
# n += 1
# i += 1
# break
# while str1[i] == ' ':
# i += 1
# i += 1
# print(n)


上一篇:字符串的小积累


下一篇:绘制方式和OpenGL枚举对应关系