Python String Methods 2

1. Python isalnum()方法  #检测字符串是否由字母和数字组成

如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
>>> 'hello'.isalnum()
True
>>> 'hello123'.isalnum()
True
>>> 'hello_123'.isalnum()
False
>>> 'this is string'.isalnum()
False
>>> 'hello world'.isalnum()
False
View Code

2. Python isalpha()方法  #检测字符串是否只由字母组成

如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False
>>> 'hello123'.isalpha()
False
>>> 'hello world'.isalpha()
False
>>> 'helloworld'.isalpha()
True
View Code

3. Python isdigit()方法   #检测字符串是否只由数字组成

如果字符串只包含数字则返回 True 否则返回 False
>>> '12345'.isdigit()
True
>>> '12345a'.isdigit()
False
View Code

4. Python islower()方法 #检测字符串是否由小写字母组成

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

>>> '2hello'.islower()
True
>>> '_hello'.islower()
True
>>> 'Hello'.islower()
False
>>> '_hellO'.islower()
False
View Code

5. Python isnumeric()方法  #检测字符串是否只由数字组成。这种方法是只针对unicode对象

注:定义一个字符串为Unicode,只需要在字符串前添加 'u' 前缀即可
>>> u'123456'.isnumeric()
True
>>> u'123a456'.isnumeric()
False
>>> u'123_456'.isnumeric()
False
View Code

6. Python isspace()方法  #检测字符串是否只由空格组成

如果字符串中只包含空格,则返回 True,否则返回 False
>>> '    '.isspace()
True
>>> '   '.isspace() #\t
True
>>> '_   '.isspace()
False
>>> '  1  '.isspace()
False
View Code

7. Python istitle()方法 #检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写

如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False
>>> 'Hello World'.istitle()
True
>>> 'Hello world'.istitle()
False
>>> 'HEllo World'.istitle()
False
>>> 'Hello World123'.istitle()
True
View Code

8. Python isupper()方法  #检测字符串中所有的字母是否都为大写

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
>>> 'HELLO WORLD'.isupper()
True
>>> 'HELLO WorLD'.isupper()
False
View Code

9. Python join()方法  #用于将序列中的元素以指定的字符连接生成一个新的字符串

>>> seq = ("a","b","c")
>>> '+'.join(seq)
'a+b+c'
>>> ' hello'.join(seq)
'a hellob helloc'
View Code

10. Python len()方法 #返回对象(字符、列表、元组等)长度或项目个数

>>> str = "hello world"
>>> len(str)
11
>>> l = [1,2,3,4,5,6]
>>> len(l)
6
View Code

 

posted @ 2017-11-09 16:46  njuptlwh  阅读(175)  评论(0编辑  收藏  举报