Python数据类型之字符串及其操作

  字符串方法

  strip方法返回去除两侧(不包括内部)空格的字符串。

x = '  x  my name is xxx!   '
print(x.strip())
>>> x  my name is xxx!

  也可以指定需要去除的字符,将他们列为参数即可(这个方法只删除开头或末尾的指定字符,因此中间的不会被删除)

x = 'x  my name is xxxx'
print(x.strip('x'))
>>>  my name is

  此时 my前面和is后面都有空格,如果字符串前面或者后面有空格,那么指定字符的方式就无效

x = ' x  my name is !xxxx  '       #x前面 xxxx后面都有空格
print(x.strip('x')) 
>>>x  my name is !xxxx

  lstrip/rstrip去除字符串左侧/右侧的空格或指定的字符

x = 'x  my name is !xxxx'
print(x.lstrip('x'))
print(x.rstrip('x'))
>>> my name is !xxx
>>>x my name is !

  count统计某个字符在字符串中出现的次数,或在字符串指定区间内完成上述操作。

x = 'swhthdaefaaituntjdqvhyrd'
print(x.count('h'))
>>> 3

  从索引值0-6范围的字符中统计h出现的次数

x = 'swhthdaefaaituntjdqvhyrd'
print(x.count('h',0,6))
>>> 2

   find方法可以在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引。如果没有找到,则返回 -1。

x = 'www.baidu.com'
print(x.find('com'))
print(x.find('cn'))
>>>10
>>>-1

  index方法用于从字符串中找出某个对象第一个匹配的索引位置,如果这个对象不再其中会报一个异常。

x = 'hello,world!'
print(x.index('o'))
>>>4

  #find和index方法类似,相同点是如果查找的字符在字符串中,那么都会返回字符串中最左端的索引位置,不同点是如果字符不在字符串中,find返回-1。index则会抛出valueError异常。

  rfind方法用来查询指定字符最后位置的索引

info = 'my name is ... and i am ... old'
print(info.rfind('m'))
>>>22

  #最后一个字符'm'的索引位置是22

  split方法通过制定分割符对字符串进行切片

url = 'www.baidu.com'
print(url.split('.'))
print(url.split('baidu'))
>>>['www', 'baidu', 'com']
>>>['www.', '.com']

  #使用逗号来替换掉字符串中指定的内容,返回的是个列表

  join方法用来连接序列中的元素,是split的逆方法

n = ['hong','huang','lan']
x = '...'
print(x.join(n))
>>>hong...huang...lan

  #用字符串(这里是'...')替代掉列表中的逗号,列表没有join方法,join方法只对字符串生效(列表的元素必须是且只能是字符串),对列表进行操作,返回字符串

  caplitalize方法用来将字符串小写首字母转换成大写

n = 'hello,world!'
print(n.capitalize())
>>>Hello,world!

  title方法将每个单词的首字母都改为大写

n = 'hello,world!'
print(n.title())
>>> Hello,World!

  upper,lower方法将字符串大写转换成大/小写

n = 'Hello,World!'
print(n.upper())
>>>HELLO,WORLD!
n = 'Hello,World!'
print(n.lower())
>>>hello,world!

  center方法填充字符串长度,使用原有字符串加填充字符构成指定长度的新的字符串

n = 'hello,world!'
print(n.center(20))
print(n.center(20,'-'))
>>>    hello,world!    
>>>----hello,world!----

  ljust,rjust方法用于指定扩展字符串长度。

n = 'hello,world!'
print(n.ljust(5))
print(n.ljust(20,'*'))
>>>hello,world!
>>>hello,world!********

n = 'hello,world!'
print(n.rjust(5))
print(n.rjust(20,'*'))
>>>hello,world!
>>>********hello,world!

  #指定长度小于字符串长度则无效

  replace把字符串中的旧字符替换成新字符,如果指定第三个参数,则替换不超过3次

x = 'this is a test'
print(x.replace('is','xxx'))
>>>thxxx xxx a test
#次数参数
str = "this is string example....wow!!! this is really string"
print(str.replace('is','was',3))
>>>thwas was string example....wow!!! thwas is really string

  以下方法只返回两个结果:True或False

  endswith判断字符串是否以某个字符结尾

  isalnum判断字符串是否由字母和数字组成

  isalpha判断字符串是否只有字母组成

  iscecimal 判断字符串是否是十进制

  isdigit判断字符串是否是整数

  isidentifier判断是不是一个合法的变量名(变量名命名规则)

  islower判断字符串是否是小写

  isnumeric判断字符串是否是整数(isdigit什么区别)

  istitle判断字符串开头是否是大写

  isupper判断字符串是否全是大写

猜你喜欢

转载自www.cnblogs.com/romacle/p/10739250.html