您的位置:首页 > 编程语言 > Python开发

【每天1分钟】PYTHON基础之数据类型-字符串(检查/查找)

2019-07-18 00:00 531 查看
版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

【每天1分钟】PYTHON基础之数据类型-字符串(检查/查找)

  • count()
    统计字符出现次数
>>> str = 'abbcccdddd'

>>> str.count('a')
1

>>> str.count('bb')
1

>>> str.count('c')
3

>>> str.count('ddd')
1

>>> str.count('e')
0
>>>
  • find/rfind()
    查找字符串
>>> str = 'abcdedcba'
>>> str.find('b')
1
>>> str.rfind('b')
7
>>>
  • index/rindex()
    字符串对应的索引值
>>> str = 'abbcccddddeddddcccbba'

>>> str.index('a')
0

>>> str.index('b')
1

>>> str.rindex('a')
20

>>> str.rindex('b')
19

>>> str.index('f')
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
str.index('f')
ValueError: substring not found

>>> str.rindex('f')
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
str.rindex('f')
ValueError: substring not found
>>>
  • endswith/startswith()
    开始于 / 结束于
>>> str = 'abbcccddddeddddcccbba'

>>> str.endswith('a')
True

>>> str.startswith('a')
True

>>> str.endswith('e')
False

>>> str.startswith('e')
False

>>> str.endswith('ba')
True

>>> str.startswith('ab')
True
>>>
  • isalnum()
    检测字符串是否由字母和数字组成
>>> str = 'iamaboy'
>>> str.isalnum()       # 只有字母和数字,返回True
True

>>> str = "i am a boy"  # 字符串中有空格
>>> str.isalnum()
False
>>>
  • isalpha()
    检测字符串是否只由字母组成
>>> str = 'iamaboy'
>>> str.isalpha()
True

>>> str = 'iamaboy2'
>>> str.isalpha()   #2不是字母
False
>>>
  • isdigit()
    检测字符串是否只由数字组成
>>> str = "123456"
>>> str.isdigit()
True

>>> str = 'iamaboy'
>>> str.isdigit()
False
>>>
  • islower()
    检测字符串是否由小写字母组成
>>> str = "I am a boy, i am 3 year's old."
>>> str.islower()
False
>>> str = "i am a boy, i am 3 year's old."
>>> str.islower()
True
>>>
  • isspace()
    检测字符串是否只由空格组成
>>> str = "       "
>>> str.isspace()
True

>>> str = "   *   "
>>> str.isspace()
False
>>>
  • istitle()
    检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
>>> str = "This Is String Example...Wow!!!"
>>> str.istitle()
True

>>> str = "This is string example....wow!!!"
>>> str.istitle()
False
>>>
  • isupper()
    检测字符串中所有的字母是否都为大写
>>> str = "THIS IS STRING EXAMPLE....WOW!!!"
>>> str.isupper()
True

>>> str = "THIS is string example....wow!!!"
>>> str.isupper()
False
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: