Python判斷字符串的構成

# istitle()
print("How Are You".istitle())  # True
print("how are you".istitle())  # False

# isspace   只有空格
print("   ".isspace())  # True
print(" 132  ".isspace())   # False

# isalpha 都是字母
print("abc".isalpha())  # True
print("123456".isalpha())  # False
print("123456abc".isalpha())  # False

# isupper 有至少一個大寫字母
print("a123456".isupper())  # False
print("A123456".isupper())  # True

# isdigit 都是數字
print(b"123456".isdigit())  # True
print("123456abc".isdigit())  # False
print("asd".isdigit())  # False

# isdecimal 只包含十進制數字則返回
print("123000".isdecimal())  # True

# isnumeric 只包含數字字符,則返回 True,否則返回 False
print("123456".isnumeric())     # True
print("一二三四".isnumeric())     # True

# isdigit, isdecimal, isnumeric 區別
num = "1"  # unicode
num.isdigit()  # True
num.isdecimal()  # True
num.isnumeric()  # True

num = "1"  # 全角
num.isdigit()  # True
num.isdecimal()  # True
num.isnumeric()  # True

num = b"1"  # byte
num.isdigit()  # True
num.isdecimal()  # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric()  # AttributeError 'bytes' object has no attribute 'isnumeric'

num = "IV"  # 羅馬數字
num.isdigit()  # True
num.isdecimal()  # False
num.isnumeric()  # True

num = "四"  # 漢字
num.isdigit()  # False
num.isdecimal()  # False
num.isnumeric()  # True


# 判斷有漢字
import re
chinese_str = "中國人民銀行"
search_ret = re.compile(u'[\u4e00-\u9fa5]')
ret = search_ret.search(chinese_str)
if ret:
    print("有漢字")
else:
    print("無漢字")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章