【Python】检测字符串的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NextAction/article/details/84978709

1. isalnum()

语法: 

str.isalnum()

返回值:

如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False

str1 = 'this2018'
str2 = 'hello world!'
print(str1.isalnum())
print(str2.isalnum())

实例输出结果为:

True
False

2. isalpha()

语法: 

str.isalpha()

返回值:

如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False

str1 = 'hello'
str2 = 'hello world!' #有空格和感叹号
print(str1.isalpha())
print(str2.isalpha())

实例输出结果为:

True
False

3. isdigit()

语法: 

str.isdigit()

返回值:

如果字符串只包含数字则返回 True 否则返回 False

str1 = '0123456789'
str2 = 'hello2018' 
print(str1.isdigit())
print(str2.isdigit())

实例输出结果为:

True
False

4. islower()

语法: 

str.islower()

返回值:

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False

str1 = 'hello0123456789'
str2 = 'Helloworld' 
print(str1.islower())
print(str2.islower())

实例输出结果为:

True
False

 5. isnumeric()

语法: 

str.isnumeric()

返回值:

如果字符串中只包含数字字符,则返回 True,否则返回 False

注:这种方法是只针对unicode对象。

str1 = u'0123456789'
str2 = u'hello0123456789'
print(str1.isnumeric())
print(str2.isnumeric())

实例输出结果为:

True
False

6. isspace()

语法: 

str.isspace()

返回值:

如果字符串中只包含空格,则返回 True,否则返回 False

str1 = '    '
str2 = 'hello world'
print(str1.isspace())
print(str2.isspace())

实例输出结果为:

True
False

 7. istitle()

语法: 

str.istitle()

返回值:

如果字符串中所有的单词拼写首字母为大写,且其他字母为小写则返回 True,否则返回 False

str1 = 'My Heart Will Go On'
str2 = 'My heart Will go on'
print(str1.istitle())
print(str2.istitle())

实例输出结果为:

True
False

8. isupper()

语法: 

str.isupper()

返回值:

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False

str1 = 'HELLO0123456789'
str2 = 'Helloworld' 
print(str1.isupper())
print(str2.isupper())

实例输出结果为:

True
False

猜你喜欢

转载自blog.csdn.net/NextAction/article/details/84978709
今日推荐