python数据类型---字符串

常量,不可变类型,所有的修改都是返回一个新的元素

str.split

根据指定参数进行切割,如果没有匹配到切割参数则返回整个字符串
rsplit表示从右往左切

str.split() 没有参数,则已空格贪婪模式切割

str1 = 'asd        \t   \n      fa     sd f'
print(str1.split())
>>['asd', 'fa', 'sd', 'f']

str.split(' ') 如果指定参数为空格,则按照空格切

print(str1.split())
>>['asd', '', '', '', '', '', '', '', '\t', '', '', '\n', '', '', '', '', '', 'fa', '', '', '', '', 'sd', 'f']

str.split(' ',maxsplit=5) maxsplit指定最大切割次数

print(str1.split(' ',maxsplit=5))
>>['asd', '', '', '', '', '   \t   \n      fa     sd f']

str.splitlines()

按照行进行切割,\r(mac) \r\n(win) \n(linux)都可识别

str1 = 'asd\t\nfa\rsd\r\nf'
print(str1.splitlines())
>>['asd\t', 'fa', 'sd', 'f']

str.partition()

根据指定参数进行一刀切,partition从左到右切,rpartition从右到左切
如果参数没有匹配到则返回空

str2 = 'https://ke.qq.com/course/458302'
print(str2.rpartition('/')[-1])
>>458302

str.replace()

替换,并返回一个新的字符串,如果参数没有匹配到,则返回原来字符串,可指定替换次数,默认全部替换

str2 = 'https://ke.qq.com/course/458302'
print(str2.replace('course','math'))
>>https://ke.qq.com/math/458302
print(str2.replace('math','course'))
>>https://ke.qq.com/course/458302

str.strip() 两头去

  • lstrip() 左边去
  • rstrip() 右边去
  • str.strip() 去掉两边的空白字符
  • str.strip('abc') 去掉两边匹配到参数的内容,发现非参数内容即停止

str.startswith()、str.endswith()

返回bool值
判断是否是指定参考开头或者结尾

其他

  • upper()转换为大写
  • lower()转换为小写
  • swapcase()交换大小写
  • isalnum() 是否是数字或数字组成
  • isalpha() 是否是字母
  • isdecimal() 是否是十进制数字
  • isnumeric() 是否是数字
  • isdigit() 是否是数字[0-9]
  • isidentifier() 是不是标识符
  • islower() 是否全部是小写
  • isupper() 是否全部是大写
  • isspace() 是否包含空字符

猜你喜欢

转载自www.cnblogs.com/zoer/p/13198908.html