统一输入字符串中不同的字符及所占比例,要求用户从键盘输入一串字符,编写一个程序,统计并输出其中英文字符,数字,空格和其他字符的个数及其在字符串中所占的百分比,
时间: 2024-11-15 13:21:31 浏览: 17
为了实现这个功能,你可以使用Python编写一个简单的程序。首先,我们需要获取用户的输入,然后遍历这个字符串,分别计数英文字符、数字、空格和其他特殊字符的数量。接下来,我们将计算每个部分在总字符数中所占的比例,并将其转换为百分比。以下是示例代码:
```python
def count_chars(input_string):
# 初始化计数器
eng_chars = 0
digits = 0
spaces = 0
others = 0
for char in input_string:
if char.isalpha():
eng_chars += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
else:
others += 1
total_chars = len(input_string)
# 计算百分比
eng_percent = (eng_chars / total_chars) * 100 if total_chars != 0 else 0
digit_percent = (digits / total_chars) * 100 if total_chars != 0 else 0
space_percent = (spaces / total_chars) * 100 if total_chars != 0 else 0
other_percent = (others / total_chars) * 100 if total_chars != 0 else 0
return {
"English Characters": eng_chars,
"Digits": digits,
"Spaces": spaces,
"Others": others,
"Percentage of English": eng_percent,
"Percentage of Digits": digit_percent,
"Percentage of Spaces": space_percent,
"Percentage of Others": other_percent,
}
# 获取用户输入
input_from_user = input("Please enter a string: ")
result = count_chars(input_from_user)
# 输出结果
for category, value in result.items():
print(f"{category}: {value} ({value:.2f}%)")
#
阅读全文