下面詳細(xì)講解如何判斷字符串的元素組成。這個(gè)案例將幫助你掌握字符串處理的基本技巧,并了解多種驗(yàn)證方法。我們從基礎(chǔ)到進(jìn)階逐步深入: 1. 基礎(chǔ)判斷方法(1)檢查字符串是否只包含字母將詳細(xì)講解如何判斷字符串的元素組成。這個(gè)案例將幫助你掌握字符串處理的基本技巧,并了解多種驗(yàn)證方法。我們從基礎(chǔ)到進(jìn)階逐步深入:1. 基礎(chǔ)判斷方法(1)檢查字符串是否只包含字母text = 'Hello'
print(text.isalpha()) # 輸出 True(純字母)
text2 = 'Hello123'
print(text2.isalpha()) # 輸出 False (2)檢查是否只包含數(shù)字
(3)檢查是否字母或數(shù)字組合mixed = 'Hello123'
print(mixed.isalnum()) # 輸出 True(字母或數(shù)字)
mixed2 = 'Hello!'
print(mixed2.isalnum()) # 輸出 False(含特殊字符) 2. 自定義條件判斷(1)檢查是否包含特定字符
(2)統(tǒng)計(jì)各類(lèi)字符數(shù)量text = 'PyThon3.8!'
lower = sum(1 for c in text if c.islower()) # 小寫(xiě)字母
upper = sum(1 for c in text if c.isupper()) # 大寫(xiě)字母
digit = sum(1 for c in text if c.isdigit()) # 數(shù)字
other = len(text) - lower - upper - digit # 其他字符
print(f'小寫(xiě):{lower},大寫(xiě):{upper},數(shù)字:{digit},其他:{other}') 3. 正則表達(dá)式進(jìn)階版
正則表達(dá)式說(shuō)明:
4. 密碼強(qiáng)度檢測(cè)案例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 ['弱', '中', '強(qiáng)', '極強(qiáng)'][strength-1]
print(password_strength('Abc123!')) # 輸出 '極強(qiáng)' 5. 字符串組成可視化
6. 綜合練習(xí)嘗試實(shí)現(xiàn)以下功能:
示例代碼框架: # 回文檢測(cè)
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. 常見(jiàn)問(wèn)題解答Q:如何判斷字符串是否全為中文?
Q:如何檢查字符串是否包含空格? print(' ' in 'hello world') # 方法1
print('hello world'.isspace()) # 方法2(檢查是否全為空格) Q:大小寫(xiě)敏感如何控制?
|
|