编写函数,统计字符串中字母和数字的个数
时间: 2024-03-24 13:13:12 浏览: 15
好的,这个问题我可以回答。以下是统计字符串中字母和数字个数的函数:
```python
def count_alphanum(string):
count_alpha = 0
count_num = 0
for i in string:
if i.isalpha():
count_alpha += 1
elif i.isdigit():
count_num += 1
return count_alpha, count_num
```
你可以调用该函数并传入字符串参数来获取字符和数字的个数。
相关问题
编写自定义函数统计字符串中字母符个数
好的,下面是一个Python的自定义函数,可以统计字符串中字母符号的个数:
```python
def count_letters(s):
count = 0
for c in s:
if c.isalpha():
count += 1
return count
```
这个函数的原理是遍历字符串中的每一个字符,如果这个字符是字母符号,则计数器加一。最后返回计数器的值,即字符串中字母符号的个数。
你可以这样调用这个函数:
```python
s = "Hello, world!"
print(count_letters(s)) # 输出 10
```
这里的字符串`s`包含了10个字母符号。
编写一个函数统计字符串中大写字母和小写字母的个数
好的,以下是实现这个功能的 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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)