编写一个函数,实现统计字符串中单词的个数并返回
时间: 2023-05-02 21:00:55 浏览: 85
可以使用 Python 编写一个函数,实现统计字符串中单词的个数并返回。
示例代码:
```python
def count_words(s):
# 利用空格将字符串拆分成单词列表
words = s.split()
# 返回单词列表的长度
return len(words)
```
使用该函数统计字符串的单词个数并输出:
```python
s = "This is a sentence."
count = count_words(s)
print(count) # 输出:4
```
在这个例子中,字符串 `s` 中包含 4 个单词,即 "This"、"is"、"a"、"sentence."。函数 `count_words` 利用 `split` 方法将字符串拆分成单词列表,再返回列表长度,即可得到单词个数。
相关问题
编写函数实现统计字符串中单词的个数并返回
可以使用以下函数来实现统计字符串中单词的个数并返回:
```python
def count_words(s):
"""
统计字符串中单词的个数并返回
"""
# 将字符串按空格分割成单词列表
words = s.split()
# 返回单词列表的长度
return len(words)
```
该函数的实现思路是将字符串按空格分割成单词列表,然后返回单词列表的长度,即单词的个数。
python编写一个函数,实现统计字符串中单词的个数并返回
以下是一个实现该功能的Python函数:
```python
def count_words(string):
"""
统计字符串中单词的个数并返回
"""
# 将字符串按空格分割成单词列表
words = string.split()
# 统计单词个数并返回
return len(words)
```
可以通过调用该函数来统计一个字符串中单词的个数,例如:
```python
string = "This is a test string."
word_count = count_words(string)
print("单词个数:", word_count)
```
输出结果为:
```
单词个数: 5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)