11.str的操作

  • 按索引取值(正向取+反向取):只能取,,不能改
msg = 'hello world'
#正向取
print(msg[0])
print(msg[5])
#反向取
print(msg[-1])
  • 切片

索引的扩展应用,从一个大字符串中拷贝出一个子字符串

msg = 'hello world'
#顾头不顾尾
res = msg[0:5]   #0可以默认不写
print(res)  #hello
print(msg)	#hello world
  • 步长
res = msg[0:5:2]  #0 2 4
print(res)      #hlo
  • 反向步长
res = msg[5:0:-1]
print(res)   #' olle'
  • 从头取到尾
res = msg[:]  #res = msg[0:11]
  • 反向倒置
res = msg[::-1]  #字符串倒过来
  • 长度len
print(len(msg))
  • 移除字符串左右两侧的空白strip
msg = '    egon    '
res = msg.strip()
print(res)
print(msg)	#不会改变原值

msg = '***e**gon***'
res = msg.strip('*')
#只去除左右两侧的*,不去中间

msg = '*/=**e**gon**()*'
res = msg.strip('*/=()')
#去除左右两侧特殊符号

lstrip('*')	#只去左边
rstrip('*')	#只去右边
  • split分割:把一个字符串按照某种分隔符进行切分,得到一个列表,默认分隔符是空格
info = 'egon 18 male'
res = info.split()
print(res)

info = 'egon:18:male'
res = info.split(':')	#指定分隔符
print(res)

info = 'egon:18:male'
res = info.split(':',1)	#指定分隔符和分割次数
print(res)
  • lower、upper
msg = 'AAbbCC'
print(msg.lower())
print(msg.upper())
  • startwith、endwith
startwith:以什么字符开头
endwith:以什么字符结尾
返回bool
  • split,rsplit
将字符串切割成列表,从左切和从右切
  • join:把列表拼接成字符串
l = ['egon','18','male']
res=":".join(l) #按照某个分隔符,把元素全为字符串的列表拼接成一个大字符串
print(res)   #纯字符串按分隔符相加
  • replace
msg = 'you can you up no can no bb'
print(msg.replace('you','YOU',1))
#替换目标  替换后目标  替换次数,不写默认全部替换
  • isdigit:判断字符串是否由纯数字组成
print('123’.isdigit())
  • find与index
msg = 'hello egon hahaah'
#找到返回起始索引
print(msg.find('e')) # 返回要找的字符串在大字符串中的起始索引
print(msg.index('e'))

#找不到索引时 
print(msg.find('xxx'))  #返回-1,代表找不到
print(msg.index('xxx'))  #抛出异常报错
  • count:统计个数
  • center:居中 ljust :内容左对齐,不够的用填充 rjust:内容右对齐 zfill:0填充,默认右对齐
print('egon'.center(50,'*'))
#字符串个数,填充物
  • expandtabs
msg = 'hello\tword'
print(msg.expandtabs(2))	#设定制表符代表的空格数为2
  • captalize:首字母大写

  • swapcase:大小写反转

  • title:每个单词的首字母大写

  • islower():是否全为xiaoxie

  • isupper()

  • istitle()

  • isalnum() #字符串由字母或数字组成结果为True

  • isalpha() #必须由字母组成,结果为True

  • isspace() #字符串由空格组成,结果为True

  • isidentifier() #是否是系统字符串或合规的自编变量名

  • is数字系列

#在python3中
num1 = b'4' #bytes
num2 = u'4' #unicode,python3中无需加u就是unicode
num3 = '四' #中文数字
num4 = 'Ⅳ' #罗马数字

#isdigt:bytes,unicode
>>> num1.isdigit()
True
>>> num2.isdigit()
True
>>> num3.isdigit()
False
>>> num4.isdigit() 
Fals
  • isnumberic:可以识别num2、num3、num4
>>> num2.isnumeric() 
True
>>> num3.isnumeric() 
True
>>> num4.isnumeric() 
True
  • isdecimal
#isdecimal:uncicode(bytes类型无isdecimal方法)
>>> num2.isdecimal() 
True
>>> num3.isdecimal() 
False
>>> num4.isdecimal() 
False
posted @ 2020-10-30 22:51  Psc-mmf  阅读(72)  评论(0)    收藏  举报