python中字符串string相关操作整理
python 字符串操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等
# 字符串替换 str=" test by lisa... ".replace("lisa","tom") str2=str # 复制字符串 str3=str+str2 #连接字符串 print(str3) print(str) print(str.lstrip()) # 去除左边空格 print(str.rstrip()) # 去除右边空格 print(str.strip()) # 去除头尾空格 print(str.replace('\n', '').replace('\r', '')) # 去除换行符 # join li=["lisa","tom"] s=",".join(li) # join连接字符串 用逗号做分隔符 print(s)
# 字符串查找 # str.find:检测字符串中是否包含子字符串str,可指定范围 s='hello world' i=s.find('world') # i=1 下标从0开始 print(i) # 是否包含指定字符串 用in判断 a="hello world hello python" b="world" print(b in a)
# 是否包含指定字符串 用in判断 s="hello world hello python" s2="world" b=s2 in s print(b) i=len(s) #字符串长度 print(i)
# 字符串切片 s="0123456789" print(s[0:3]) # 截取第一位到第三位的字符 print(s[5:]) # 截取第6个字符到结尾 print(s[::-1]) # 字符串反序 # 9876543210 # 方返回指定长度的字符串,原字符串右对齐,前面填充0 s="123" str2=s.zfill(6) print(str2) #000123
其他查找 .find(str),str存在字符串中返回下标索引值,不存在返回-1 .rfind(str),str存在字符串中,查找顺序为从右向左,其它与find一样 .index(str),存在返回下标索引值,不存在报异常 .rindex(str),存在返回下标索引值,查找顺序为从右向左,其它与index一样 .count(str[,起始,结束]),查找指定字符串中该字符出现的总次数 分割 .split(str[,n]),以str为分隔符(分割后丢失),将字符串分割为多个字符串,n可指定最多的分割次数 .partition(str),已指定字符做为一个部分,分割两边,生成三部分的字符串 .splitlines(),按照行进行分割,返回一个包含各行作为元素的列表 对齐格式化 .ljust(width)返回一个原字符串左对齐,并默认使用空格补充至长度为width的字符串 .rjust(width)返回一个原字符串右对齐,并默认使用空格补充至........... .center(width) 返回一个原字符居中,并使用空格补充至width长度的新字符串 检查 .startswith(str),检查字符串是否以指定字符开头,是则返回Turn,否则返回False .endswith(str),检查字符串是否以指定字符结尾,是则返回Turn,否则为False .isalpha(),检查字符串是否都是字母,是返回Turn,否则返回False .isdigit(),检查字符串是否只包含数字,是返回Turn,否则返回False .isalnum(),检查字符串是否都是字母或数字,是返回Turn,否则返回False .isspace(),检查字符串是否只包含空格,是返回Turn,否则返回False
近期评论