Python函数:如何计算字符串中单词的数量?
发布时间:2023-07-01 19:00:50
要计算字符串中单词的数量,可以使用split()函数将字符串按照空格分割成一个单词列表,然后通过len()函数获取列表的长度即可。
以下是一个示例代码:
def count_words(string):
words = string.split()
return len(words)
# 测试示例
string = "Hello, this is a sample string."
word_count = count_words(string)
print("单词数量:", word_count)
输出结果为:
单词数量: 6
这个示例中,输入的字符串是"Hello, this is a sample string.",分割后得到的单词列表为["Hello,", "this", "is", "a", "sample", "string."],列表的长度为6,即字符串中单词的数量。
