python判断字符串只包含数字,小写字母,大写字母
时间: 2023-07-17 12:58:56 浏览: 67
你可以使用正则表达式来判断字符串是否只包含数字、小写字母和大写字母。下面是一个示例代码:
```python
import re
def is_alphanumeric(input_string):
pattern = "^[a-zA-Z0-9]+$"
return bool(re.match(pattern, input_string))
# 测试字符串
test_string = "Abc123"
if is_alphanumeric(test_string):
print("字符串只包含数字、小写字母和大写字母")
else:
print("字符串包含其他字符")
```
在上面的代码中,`is_alphanumeric`函数使用`re.match`函数来检查输入的字符串是否与指定的正则表达式模式匹配。如果匹配成功,则返回True,表示字符串只包含数字、小写字母和大写字母;否则返回False,表示字符串包含其他字符。
相关问题
python中输出字符串中大写字母 小写字母 数字 空格的个数
可以使用循环遍历字符串中的每个字符,然后判断字符的类型并计数。具体代码如下:
```python
s = 'Hello World 123'
upper_count = 0
lower_count = 0
digit_count = 0
space_count = 0
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
elif c.isdigit():
digit_count += 1
elif c.isspace():
space_count += 1
print("大写字母个数:", upper_count)
print("小写字母个数:", lower_count)
print("数字个数:", digit_count)
print("空格个数:", space_count)
```
输出结果为:
```
大写字母个数: 2
小写字母个数: 8
数字个数: 3
空格个数: 2
```
用Python正则表达式判断字符串中既有大写字母又有小写字母
可以使用Python内置的re模块,利用正则表达式来判断字符串中是否既有大写字母又有小写字母。以下是一个示例代码:
```python
import re
def has_upper_and_lower(text):
# 定义正则表达式,匹配至少一个大写字母和至少一个小写字母
pattern = re.compile(r'[A-Z]+.*[a-z]+|[a-z]+.*[A-Z]+')
# 判断是否匹配成功
if pattern.match(text):
return True
else:
return False
# 测试
print(has_upper_and_lower('AbcDEF')) # True
print(has_upper_and_lower('abc')) # False
print(has_upper_and_lower('XYZ')) # False
print(has_upper_and_lower('123aBc')) # True
```
在上面的代码中,我们定义了一个名为`has_upper_and_lower`的函数,它接受一个字符串作为参数。函数内部使用`re.compile`方法创建了一个正则表达式对象,该正则表达式可以匹配至少一个大写字母和至少一个小写字母。然后使用`pattern.match`方法尝试对传入的字符串进行匹配,如果匹配成功则返回True,否则返回False。
注意,上述正则表达式的意思是:在字符串中,先匹配至少一个大写字母,后面紧跟着任意个字符(包括换行符),再匹配至少一个小写字母;或者先匹配至少一个小写字母,后面紧跟着任意个字符(包括换行符),再匹配至少一个大写字母。这样可以确保字符串中既有大写字母又有小写字母。