if not s[i].isalnum():
时间: 2024-05-31 08:07:23 浏览: 21
This code checks if the character at index i in the string s is alphanumeric or not.
If the character is not alphanumeric (i.e., not a letter or a digit), then the code within the if statement will execute.
This code is commonly used in string processing to filter out non-alphanumeric characters from a string.
相关问题
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 also ignore any whitespace characters or special characters t hat are not letters or numbers. Example: Input: hello world Output: 7 (unique characters are (h, e, l, o, w, r, d))
Sure, here's some Python code that should do the trick:
```python
def count_unique_chars(string):
# Remove whitespace and special characters
string = ''.join(c for c in string if c.isalnum())
# Count unique characters
unique_chars = set(string)
count = len(unique_chars)
return count
```
Here's how you can use the function to count the unique characters in a string:
```python
string = input("Enter a string: ")
count = count_unique_chars(string)
print("Number of unique characters:", count)
```
For example, if you enter "hello world", the program will output:
```
Number of unique characters: 7
```
输入一个字符串,判断该字符串是否为回文,只考虑数字和字母字符,字母的大小写没有区别
示例:
输入:"A man, a plan, a canal: Panama"
输出:true
输入:"race a car"
输出:false
代码实现:
```python
class Solution:
def isPalindrome(self, s: str) -> bool:
# 将字符串转为小写
s = s.lower()
# 定义双指针,i指向字符串头部,j指向字符串尾部
i, j = 0, len(s) - 1
while i < j:
# 判断字符是否为数字或字母
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
# 如果两个字符相同,则继续比较
elif s[i] == s[j]:
i += 1
j -= 1
# 如果两个字符不同,则直接返回false
else:
return False
return True
```