Python实现计算字符串中单词个数的函数
发布时间:2023-12-04 11:07:36
要实现计算字符串中单词个数的函数,可以使用以下方法:
def count_words(string):
words = string.split() # 将字符串按照空格分割成单词列表
return len(words) # 返回单词列表的长度,即单词个数
这个函数使用split()方法将字符串按照空格分割成单词列表,然后返回列表的长度即可得到单词个数。
以下是一个使用例子:
string = "Hello world! This is a sample string."
word_count = count_words(string)
print("单词个数:", word_count)
输出结果:
单词个数: 7
该例子中,字符串"Hello world! This is a sample string."包含7个单词,所以输出结果是7。
