python之字符串

来源:互联网 发布:单词社交网络怎么样 编辑:程序博客网 时间:2024/05/01 01:17

用引号包括起来的集合称之为字符串,其引号可以是单引号,双引号,三引号(单/双),三引号可以将复杂的字符串进行复制,允许一个字符串跨多行,字符串可包含制表符、换行符、以及其它特殊符号。

str1=’hello’
str2=”ligbee”
str2=”’the blog”’


字符串运算符 p=’python’

运算符 解释 使用 + 字符串连接 p+p = pythonpython * 重复输出字符串 p*2 = pythonpython [] 通过索引获取字符 p[0]= p [:] 截取字符串一部分 p[1:] = ython in 成员运算符 ‘p’ in p = true not in 成员运算符 ‘a’ not in p = false r or R 原始字符串,转义失效 r’python\n’ = python\n

字符串格式化

python 格式化与 C 一样使用占位符%

'the %s was created in %d' % ('python',1989)'the python was created in 1989'

字符串函数 p=’the python was created in 1989’
start=0 end=len(p)
查找拥有方法,p. Tab
查找使用方法,help(p.find)

函数 解释 使用 find 返回对应字符串位置,查找不到返回-1 p.find(‘python’,start,end) rfind 从右边开始查找,返回对应字符串位置,查找不到返回-1 p.rfind(‘python’,start,end) index 返回对应字符串位置,查找不到报错 p.index(‘python’,start,end) rindex 从右边开始查找,返回对应字符串位置,查找不到报错 p.rindex(‘python’,start,end) count 返回对应字符串个数 p.count(‘python’,start,end) decode 以encoding指定的编码解码字符串 p.decode(encoding=’UTF-8’,errors=’strict’) encode 以encoding指定的编码编码字符串 p.encode(encoding=’UTF-8’,errors=’strict’) replace 将str1替换为str2 p.replace(str1,str2,num(替换次数)) split 以指定分隔符 p.split(” “,num) capitalize 首字符大写 p.capitalize center 返回左右被空格填充的长度为num的字符串,居中 p.center(num) ljust 左对齐 p.ljust(num) rjust 右对齐 p.rjust(num) endswith 检查字符串是否以str结尾 p.endswith(str,start,end) startswith 检查字符串是否以str开头 p.startswith(str,start,end) expandtabs 将tab转换为空格,默认空格数为8 p.expandtabs(8) isalnum 至少有一个数字并且所有字符都是数字或字母 p.isalnum() isalpha 至少有一个字符并且所有字符都是字母(不包括空格) p.isalpha() isdecimal 只包含十进制 isdigit 只包含数字 islower 判断都是小写 isupper 判断都是大写 isspace 只有空格 lower 转换为小写 upper 转换为大写 join 连接字符串str p.join(str) lstrip 截掉左边空格 p.lstrip() rstrip 截掉右边空格 p.rstrip() partition 以str分割线,分成三部分,返回元组 p.partition(str) rpartition 以str分割线,从右分成三部分,返回元组 p.rpartition(str) zfill 右对齐,0填充 p.zfill(num)
0 0