Count 计数功能,返回自定字符在字符串当中的个数
a=(‘hello world’)
b=a.find(‘o’)
print(b)
Find 查找,返回从左第一个指定字符的索引,找不到返回-1
a=(‘hello world’)
b=a.find(‘o’)
print(b)
Rfind 查找,返回从右第一个指定字符的索引,找不到返回-
a=(‘hello world’)
b=a.rfind(‘o’)
print(b)
Index 查找,返回从左第一个指定字符的索引,找不到报错
a=(‘hello world’)
b=a.index(‘o’)
print(b)
Rindex 查找,返回从右第一个指定字符的索引,找不到报错
a=(‘hello world’)
b=a.rindex(‘o’)
print(b)
字符串的分割 partition 把mystr以str分割成三部分,str前,str自身和str后
a=(‘hello world python’)
b=a.partition(‘world’)
print(b)
字符串的分割split 按照指定的内容进行分割
a=(‘hello world python’)
b=a.split(‘ld’)
print(b)
字符串的替换{replace:从左到右替换指定的元素,可以指定替换的个数,默认全部替换}
{translate按照对应关系来替换内容 from string import maketrans}
s=‘hello world python’
uo=‘world’
ou=‘okler’
s3=str.maketrans(uo,ou)
s4=s.translate(s3)
print(s4)
字符串的修饰
center 让字符串在指定的长度居中,如果不能居中左短右长,可以指定填充内容,默认以空格填充
ljust 让字符串在指定的长度左齐,可以指定填充内容,默认以空格填充
rjust 让字符串在指定的长度右齐,可以指定填充内容,默认以空格填充
zfill 将字符串填充到指定的长度,不足地方用0从左开始补充
format 按照顺序,将后面的参数传递给前面的大括号
Strip 默认去除两边的空格,去除内容可以指定
rstrip 默认去除右边的空格,去除内容可以指定
lstrip 默认去除左边的空格,去除内容可以指定
左边加*
s=‘hello’
s1=s.rjust(15,’*’)
print(len(s1))
print(s1)
a=(‘hello world python’)
b=a.replace(‘h’,‘b’,1)
print(b)
format替换
a=‘zs’
b=11
c=‘大家好我叫{}!今年年龄{}’.format(a,b)
print©
c=‘大家好,我叫{a},今年年龄{b}’.format(a=‘zs’,b=‘18’)
print©
c=‘大家好,我叫{a},今年年龄{b}’
print(c.format(a=‘zs’,b=‘23’)
字符串编码
encode是编码,将字符串转换成字节码。str—>byte
decode是解码,将字节码转换成字符串。byte—>str
s=‘我’
ret=s.encode()
print(ret)
s2=ret.decode()
print(s2)
#指定编码表
ret2=s.encode(encoding=‘gbk’)
print(ret2)
s3=ret2.decode(encoding=‘gbk’)
print(s3)