码迷,mamicode.com
首页 > 其他好文 > 详细

字符串相关操作

时间:2019-03-06 01:08:12      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:case   info   int   最小值   nbsp   使用   rip   pre   字符串方法   

  所有标准的序列操作(索引,分片,乘法,判断成员资格,长度,取最小值和最大值)对字符串同样适用,但字符串都是不可变的,所以不可进行分片赋值操作。

  字符串方法

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

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

  也可以指定需要去除的字符,将他们列为参数即可

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

  #lstrip/rstrip去除字符串左侧/右侧的空格回车。

  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

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

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

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

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

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

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

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

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

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

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

  swapcase方法将字符串大小写转换

n = ‘Hello,World!‘
print(n.swapcase())
>>>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判断字符串是否全是大写

 

字符串相关操作

标签:case   info   int   最小值   nbsp   使用   rip   pre   字符串方法   

原文地址:https://www.cnblogs.com/romacle/p/10480731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!