编写函数count,统计参数字符串中字母和其他字符的个数
时间: 2023-11-19 19:55:52 浏览: 78
可以使用Python内置的字符串方法isalpha()来判断一个字符是否为字母,然后遍历字符串统计即可。代码如下:
```python
def count(s):
letters = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
else:
others += 1
return letters, others
```
调用这个函数,可以得到字符串中字母和其他字符的个数:
```python
s = "Hello, world! 123"
letters, others = count(s)
print(f"letters: {letters}, others: {others}")
# 输出:letters: 10, others: 9
```
在这个例子中,字符串中有10个字母和9个其他字符。
相关问题
编写函数,统计字符串中字母和数字的个数
好的,这是一个可以回答的问题。以下是一个可能的实现,统计给定字符串中字母和数字的个数。
```python
def count_alphanumeric(s):
num_count = 0
alpha_count = 0
for c in s:
if c.isnumeric():
num_count += 1
elif c.isalpha():
alpha_count += 1
return alpha_count, num_count
```
这个函数会返回一个包含两个整数的元组,第一个整数表示字母的个数,第二个整数表示数字的个数。您可以像这样使用它:
```python
s = 'hello 123 world'
alpha_count, num_count = count_alphanumeric(s)
print(f'字母个数:{alpha_count},数字个数:{num_count}')
```
输出:
```
字母个数:10,数字个数:3
```
希望这可以帮到您!
编写一个函数统计字符串中大写字母和小写字母的个数
好的,以下是实现这个功能的 Python 代码:
```python
def count_upper_lower(s):
upper_count = 0
lower_count = 0
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
return upper_count, lower_count
```
这个函数接受一个字符串作为参数,然后遍历字符串中的每个字符,判断它是大写字母还是小写字母,最后返回一个元组,包含大写字母的数量和小写字母的数量。你可以调用这个函数来统计任何字符串中大写字母和小写字母的个数,例如:
```python
s = "Hello, World!"
upper_count, lower_count = count_upper_lower(s)
print("大写字母数量:", upper_count)
print("小写字母数量:", lower_count)
```
输出结果为:
```
大写字母数量: 2
小写字母数量: 8
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)