python入门到脱坑经典案例—判断字符串的 元素组成
下面详细讲解如何判断字符串的元素组成。这个案例将帮助你掌握字符串处理的基本技巧,并了解多种验证方法。我们从基础到进阶逐步深入:
1. 基础判断方法
(1)检查字符串是否只包含字母将详细讲解如何判断字符串的元素组成。这个案例将帮助你掌握字符串处理的基本技巧,并了解多种验证方法。我们从基础到进阶逐步深入:
1. 基础判断方法
(1)检查字符串是否只包含字母
text = "Hello"
print(text.isalpha()) # 输出 True(纯字母)
text2 = "Hello123"
print(text2.isalpha()) # 输出 False
(2)检查是否只包含数字
num = "12345"
print(num.isdigit()) # 输出 True(纯数字)
num2 = "123abc"
print(num2.isdigit()) # 输出 False
(3)检查是否字母或数字组合
mixed = "Hello123"
print(mixed.isalnum()) # 输出 True(字母或数字)
mixed2 = "Hello!"
print(mixed2.isalnum()) # 输出 False(含特殊字符)
2. 自定义条件判断
(1)检查是否包含特定字符
def contains_char(text, char):
return char in text # 使用in关键字
print(contains_char("apple", "p")) # 输出 True
print(contains_char("apple", "z")) # 输出 False
(2)统计各类字符数量
text = "PyThon3.8!"
lower = sum(1 for c in text if c.islower()) # 小写字母
upper = sum(1 for c in text if c.isupper()) # 大写字母
digit = sum(1 for c in text if c.isdigit()) # 数字
other = len(text) - lower - upper - digit # 其他字符
print(f"小写:{lower},大写:{upper},数字:{digit},其他:{other}")
3. 正则表达式进阶版
import re
def check_composition(text):
if re.fullmatch(r'[A-Za-z]+', text): # 仅字母
return "纯字母"
elif re.fullmatch(r'\d+', text): # 仅数字
return "纯数字"
elif re.fullmatch(r'[A-Za-z\d]+', text): # 字母+数字
return "字母数字组合"
else:
return "包含特殊字符"
print(check_composition("Hello")) # 输出 "纯字母"
print(check_composition("123!@#")) # 输出 "包含特殊字符"
正则表达式说明:
- [A-Za-z]:匹配所有字母
- \d:匹配数字(等价于[0-9])
- +:匹配前一个字符1次或多次
- fullmatch:要求整个字符串匹配模式
4. 密码强度检测案例
def password_strength(pwd):
if len(pwd) < 8:
return "弱密码:至少8位"
has_upper = any(c.isupper() for c in pwd)
has_lower = any(c.islower() for c in pwd)
has_digit = any(c.isdigit() for c in pwd)
has_special = not pwd.isalnum()
strength = 0
if has_upper: strength += 1
if has_lower: strength += 1
if has_digit: strength += 1
if has_special: strength += 1
return ["弱", "中", "强", "极强"][strength-1]
print(password_strength("Abc123!")) # 输出 "极强"
5. 字符串组成可视化
from collections import Counter
text = "Python3.8 发布!2020年"
counter = Counter(text)
print("字符频率统计:")
for char, count in counter.items():
print(f"'{char}': {count}次")
# 输出示例:
# 'P': 1次
# 'y': 1次
# '!': 1次
# '2': 2次 等
6. 综合练习
尝试实现以下功能:
- 检查字符串是否是回文(正反读相同)
- 统计字符串中每个元音字母的出现次数
- 验证电子邮件格式是否合法(包含@和.)
示例代码框架:
# 回文检测
def is_palindrome(text):
clean = ''.join(c.lower() for c in text if c.isalnum())
return clean == clean[::-1]
print(is_palindrome("A man, a plan, a canal: Panama")) # 输出 True
7. 常见问题解答
Q:如何判断字符串是否全为中文?
def is_chinese(text):
return all('\u4e00' <= char <= '\u9fff' for char in text)
Q:如何检查字符串是否包含空格?
print(" " in "hello world") # 方法1
print("hello world".isspace()) # 方法2(检查是否全为空格)
Q:大小写敏感如何控制?
text = "Hello"
print(text.lower() == "hello") # 转换为小写比较