-
如何表示字符串
str_example = “example” 或者 str_example = ‘example’,还有’’’’’'或者""""""。
三对引号的可完整保留字符串内的格式。 -
字符串的切片
规则:a[开始:结束:步长]
注意:下标从0开始,往后依次加1,总长度为len(name), 倒数第一个是-1,往前依次类推。取值原则是“取前不取后”。
举例:
a=“abcdefg” #步长不填写默认是1,是正方向切片(由左到右)
a[0:3] = “abc” #等同于 a[:3] 开始下标如果是0可省略
a[1:4] = “bcd”
a[2:-1] = “cdef”
a[-2:-5:-1] = “fed” #步长为-1,代表反方向切片(由右到左)
a[::-1] = “gfedcba” #字符串反转 -
字符串常用方法
find()
举例:str_example.find(‘abc’, start=0, end=len(str_example))
查询’abc’是否包含在str_example字符串中。如有则返回第一个索引值,否则返回-1。start默认为0,end默认是字符串长度。rfind()
举例:str_example.rfind(‘abc’, start=0, end=len(str_example))
从右边开始查询的方法,其他特点类似find()。index()
举例:str_example.index(‘abc’, start=0, end=len(str_example))
类似于find()的查询方法,不同在于查询不到时,此方法报异常。rindex()
举例:str_example.rindex(‘abc’, start=0, end=len(str_example))
从右边开始的index()count()
举例:str_example.count(‘abc’, start=0, end=len(str_example))
返回开始和结束下标范围内的’abc’出现的次数。没有出现过返回0。startswith()
举例:str_example.startswith(obj)
检查字符串是否以obj开头,是返回True。否则返回Falseendswith()
举例:str_example.endswith(obj)
检查字符串是否以obj结尾,是返回True。否则返回Falsereplace()
举例:str_example.replace(‘a’, ‘b’, str_example.count(‘a’))
把str_example中的’a’替换为’b’,默认次数为count()值,也可通过第三个参数传入替换次数。split()
举例:str_example.split(str, num)
以str为分隔符将str_example切片,返回结果是list。如果num有值,则分割出num+1个元素。此方法不带参数时,默认以 空格 \t \n 这样的特殊符号为标记切割。splitlines()
举例:str_example.splitlines()
按照换行符\n分割,返回一个listpartition()
举例:str_example.partition(str)
将str_example字符串以首次出现的str分割成三部分,即首次出现的str前面的部分,str,首次出现的str后面的部分。rpartition()
举例:str_example.partition(str)
从右边开始的partition()。capitalize()
举例:str_example.capitalize()
将字符串首字母大写。title()
举例:str_example.title()
将字符串中的每个单词首字母大写,即大驼峰结构。lower()
举例:str_example.lower()
将字符串中的所有大写字母转为小写。upper()
举例:str_example.upper()
将字符串中的所有小写字母转为大写。ljust()
举例:str_example.ljust(width_num, str)
返回一个原字符串左对齐,并使用str(可不填,默认是空格)填充到长度为width_num的字符串。rjust()
举例:str_example.rjust(width_num, str)
返回一个原字符串右对齐,并使用str(可不填,默认是空格)填充到长度为width_num的字符串。center()
举例:str_example.center(width_num, str)
返回一个原字符串居中,并使用str(可不填,默认是空格)填充到长度为width_num的字符串。isalpha()
举例:str_example.isalpha()
判断str_example所有字符是否都是字母,是返回True,否则返回False。isdigit()
举例:str_example.isdigit()
判断str_example是否都是数字组成,是返回True,否则返回False。isalnum()
判断str_example只是由字母或者数字组成,是返回True,否则返回False。isspace()
举例:str_example.isspace()
判断str_example是否只包含空格,是返回True,否则返回False。join(list)
举例:str_example.join([‘a’, ‘b’, ‘c’])
将list中的元素以str_example为连接符拼接成一个新的字符串。要求list中元素都是字符串。strip()
举例:str_example.strip()
去除str_example字符串的首尾空格。也包括制表位\t和换行符\n。
Python学习之路:字符串
最新推荐文章于 2022-09-23 13:26:08 发布