3. Calculate the number of characters: write a program to receive a character string and a character composed of letters, numbers and spaces, and then output the number of characters contained in the input character string, regardless of case. Input: ABAOP123 A. Output: 2. 4. Enter a line of characters and count the numbers of English letters, spaces, numbers and other characters.
时间: 2023-11-27 15:51:35 浏览: 112
从键盘上输入一串英文字符(不含空格与其他字符),统计每个字符的数目,并输出字母及相应的数目。
Here are two programs - one for calculating the number of a specific character in a string, and another for counting the number of different types of characters in a string:
Program 1: Counting the number of a specific character in a string
```python
string = input("Enter a string: ")
char = input("Enter a character: ")
count = 0
for c in string:
if c.lower() == char.lower():
count += 1
print(f"The string '{string}' contains {count} instances of the character '{char}'.")
```
Program 2: Counting the number of different types of characters in a string
```python
string = input("Enter a string: ")
num_letters = 0
num_spaces = 0
num_numbers = 0
num_other = 0
for c in string:
if c.isalpha():
num_letters += 1
elif c.isspace():
num_spaces += 1
elif c.isdigit():
num_numbers += 1
else:
num_other += 1
print(f"The string '{string}' contains:")
print(f"- {num_letters} letters")
print(f"- {num_spaces} spaces")
print(f"- {num_numbers} numbers")
print(f"- {num_other} other characters")
```
阅读全文