下标
name = 'abcdef' print(name[0]) print(name[1]) print(name[2]) # a # b # c
切片
# 切片的语法:[起始:结束:步长] name = 'abcdef' print(name[0:3]) # abc print(name[2:]) # cdef print(name[1:-1]) # bcde print(name[::-2]) # fdb print(name[1:5:2]) # bd print(name[5:1:-2]) # fd print(name[::-1]) # fedcba
字符串操作
mystr = 'hello world wxhwcm and wiozxcpp' # 检测 world 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1 print(mystr.find("world")) print(mystr.find("world", 0, len(mystr))) # 6 # 6 # 跟find()方法一样,只不过如果str不在 mystr中会报一个异常 print(mystr.index("world", 0, len(mystr))) # 6 # 返回 str在start和end之间 在 mystr里面出现的次数 print(mystr.count("o", 0, len(mystr))) # 2 # 把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次. print(mystr.replace("world", "zhangsan", mystr.count("world"))) # hello zhangsan itcast and itcastcpp # 以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串 print(mystr.split(" ", 2)) # ['hello', 'world', 'itcast and itcastcpp'] # 把字符串的第一个字符大写 print(mystr.capitalize()) # Hello world itcast and itcastcpp # 把字符串的每个单词首字母大写 print(mystr.title()) # Hello World Itcast And Itcastcpp # 检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False print(mystr.startswith("hello")) # True # 检查字符串是否以obj结束,如果是返回True,否则返回 False print(mystr.endswith("cpp")) # True # 转换 mystr 中所有大写字符为小写 mystr.lower() # 转换 mystr 中所有小写字母为大写 mystr.upper() # 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串 mystr.ljust(40) # 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串 mystr.rjust(40) # 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串 mystr.center(40) # 删除 mystr 左边的空白字符 mystr.lstrip() # 删除 mystr 字符串末尾的空白字符 mystr.rstrip() # 删除 mystr 字符串两端的空白字符 mystr.strip() # 类似于 find()函数,不过是从右边开始查找 mystr.rfind("xh", 0, len(mystr)) # 类似于 index(),不过是从右边开始 mystr.rindex("o", 0, len(mystr)) # 把mystr以str分割成三部分,str前,str和str后 print(mystr.partition("wxhwcm")) # ('hello world ', 'wxhwcm', ' and wiozxcpp') # 类似于 partition()函数,不过是从右边开始. print(mystr.rpartition("c")) # ('hello world wxhwcm and wiozx', 'c', 'pp') # 按照行分隔,返回一个包含各行作为元素的列表 mystr.splitlines() # 如果 mystr 所有字符都是字母 则返回 True,否则返回 False mystr.isalpha() # 如果 mystr 只包含数字则返回 True 否则返回 False mystr.isdigit() # 如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False mystr.isalnum() # 如果 mystr 中只包含空格,则返回 True,否则返回 False mystr.isspace() # mystr 中每个字符后面插入str,构造出一个新的字符串 print("-o-".join("hive")) # h-o-i-o-v-o-e