python---字符串判断字母/数字等...

#字符串中判断字符
 
#1. isalpha()判断字符串中所有都是字母,是子字母 返回True,反之False
 
strs = "HelloWorld"
strs.isalpha()
返回true
 
#2. isdigit()判断字符串中所有都是数字,是数字 返回True,反之False
 
num = "123456"
num.isdigit()
返回true
 
#3. isspace()判断字符串中所有都是空格,有空白,返回True,反之False
 
space = "   "
space.isspace()
返回true
 
#4. istitle()判断所有字符的首字母为大写,如标题,是为True,反之为False
 
title = "Chinese"
title.istitle()
返回True
 
#5. isalnum()判断字符串中字母或者数字,是为True,反之为False
 
alunm = "sad132"
alunm.isalnum()
返回True
 
#6.  isupper()判断字符都是大写,是为True,反之为False
 
upper = "ASDS"
print(upper.isupper())
返回True
 
#7. islower()判断字符串都是小写,是为True,反之为False
 
lower = "asfa"
print(lower.islower())
返回True
 
#8. isidentifier()判断字符串是否为非法字符,是非法字符返回False
 
identifier = "@^&#@#*($"
print(identifier.identifier())
返回False
 
 
-------------------------------------------------------------------------------------------------------
拓展练习题: 来自编程100题【程序17】
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
 
string = input("输入一串任意字符: ")

number = 0
strs = 0
space = 0
other = 0
for i in string:
    if i.isalpha():
        strs += 1
    elif i.isdigit():
        number += 1
    elif i.isspace():
        space += 1
    else:
        other += 1
print("数字:%d,字母:%d,空格:%d,其他:%d"%(number,strs,space,other))
以下运行:
-------------------------------------------------------------------------------------------------------

PS C:Usersadmin> & python e:/练习文档/python100.py
输入一串任意字符: dfsgdfgs dsfs 354134 sdfa
数字:6,字母:16,空格:4,其他:0

 
原文地址:https://www.cnblogs.com/liaolei123/p/13163970.html