python接收一个字符串,分别统计大写字母
时间: 2023-05-03 11:01:37 浏览: 79
可以使用Python中的计数函数来统计一个字符串中每个字母出现的次数,然后将统计结果输出即可。例如:
```python
s = 'python接收一个字符串,分别统计大写字母'
count = {} # 创建一个空字典用于存储统计结果
for c in s:
if c.isalpha(): # 如果是字母
count[c] = count.get(c, 0) + 1 # 将该字母的计数加1
# 输出统计结果
for c in sorted(count):
print("{}:{}".format(c, count[c]))
```
输出结果为:
```
A:0
B:0
C:0
D:0
E:0
F:0
G:0
H:0
I:2
J:1
K:0
L:0
M:0
N:4
O:1
P:1
Q:0
R:4
S:2
T:3
U:0
V:0
W:0
X:0
Y:0
Z:0
a:3
b:1
c:1
d:3
e:11
f:2
g:0
h:1
i:2
j:1
k:2
l:2
m:2
n:4
o:4
p:2
q:1
r:3
s:3
t:6
u:3
v:0
w:0
x:1
y:2
z:0
```
相关问题
编写函数接收一个字符串分别统计大写字母小写字母数字其他字符的个数
以下是Python语言的代码实现:
```python
def count_chars(s):
upper_count = 0
lower_count = 0
digit_count = 0
other_count = 0
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
elif c.isdigit():
digit_count += 1
else:
other_count += 1
return upper_count, lower_count, digit_count, other_count
```
该函数接收一个字符串作为参数,使用循环遍历字符串中的每个字符,根据字符的类型增加相应的计数器。最后返回各种字符的数量。可以使用多重赋值来获取返回值中的各项数量:
```python
s = "Hello, World! 123"
upper_count, lower_count, digit_count, other_count = count_chars(s)
print("Upper case count:", upper_count)
print("Lower case count:", lower_count)
print("Digit count:", digit_count)
print("Other count:", other_count)
```
输出如下:
```
Upper case count: 2
Lower case count: 8
Digit count: 3
Other count: 3
```
编写函数,接收一个字符串,分别统计大写字母
和小写字母的个数,并返回一个字典,键为'upper'和'lower',值为对应的个数。
可以使用Python内置函数isupper()和islower()来判断字符是否为大写或小写字母。
以下是示例代码:
```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': upper_count, 'lower': lower_count}
```
使用示例:
```python
s = 'Hello World'
result = count_upper_lower(s)
print(result) # {'upper': 2, 'lower': 8}
```