Write a program that takes a string input from the user and counts the number of unique characters in the string. Note:The program should only count each unique character once, even if it appears multiple times i n the input string. The program should als
时间: 2024-03-06 12:46:41 浏览: 112
o ignore spaces and special characters.
Sure, here's a Python program that does what you asked:
```
def count_unique_chars(string):
unique_chars = set()
for char in string:
if char.isalnum():
unique_chars.add(char.lower())
return len(unique_chars)
user_input = input("Enter a string: ")
print("Number of unique characters:", count_unique_chars(user_input))
```
Explanation:
- The `count_unique_chars` function takes a string as input and returns the number of unique characters in it.
- We create an empty set called `unique_chars` to keep track of unique characters as we iterate through the string.
- For each character in the string, we check if it is alphanumeric (i.e., a letter or a number), and convert it to lowercase using the `lower()` method. If it is, we add it to the `unique_chars` set.
- Finally, we return the length of the `unique_chars` set, which gives us the number of unique characters in the string.
- In the main program, we prompt the user to enter a string, and then call the `count_unique_chars` function on it. The result is printed to the console.
I hope this helps! Let me know if you have any further questions.
阅读全文