用python对一个字符串的检查函数,验证字符串是否只包含数字或字母
时间: 2024-05-05 19:18:30 浏览: 14
可以使用Python内置函数isalnum()来检查一个字符串是否只包含数字或字母:
```python
def is_alphanumeric(s):
return s.isalnum()
# 测试代码
print(is_alphanumeric('hello123')) # True
print(is_alphanumeric('123')) # True
print(is_alphanumeric('hello!')) # False
```
当然,也可以使用正则表达式来实现:
```python
import re
def is_alphanumeric(s):
pattern = re.compile('[a-zA-Z0-9]+')
return bool(pattern.match(s))
# 测试代码
print(is_alphanumeric('hello123')) # True
print(is_alphanumeric('123')) # True
print(is_alphanumeric('hello!')) # False
```
希望对您有所帮助!