jinying8869 发表于 2015-11-30 08:36:44

Python String的一些方法

  0x01 count



str.count(sub[, start[, end]])

  用来统计字符串中某个字符的个数



1 text = "abcabcabc"
2 text.count("a")
3 #output: 3
4 text.count("a", 0)
5 #output: 3
6 text.count("a", 2, 4)
7 #output: 1
  
  0x02 find



1 str.find(sub[, start[, end]])
  查找字符串中的某个字符或者字符串,并返回index



1 text = "abcabcabc"
2 text.find("a")
3 #output: 0
4 text.find("a", 1)
5 #output: 3
6 text.find("a", 1, 2)
7 #output: -1
8 text.find("ab")
9 #output: 0
  
  0x03 index



str.index(sub[, start[, end]])
  和find的作用相同,但是找不到下标会返回ValueError
  
  0x04 join




str.join(iterable)
  以str作为分隔符来连接字符



1 >>> str = ["This","is","Mr.xt's", "blog"]
2 >>> ''.join(str)
3 "ThisisMr.xt'sblog"
4 >>> ' '.join(str)
5 "This is Mr.xt's blog"
6 >>> ','.join(str)
7 "This,is,Mr.xt's,blog"
  
  0x05 split



1 str.split(sep=None, maxsplit=-1)
  用来分割字符串,sep为分割符,第二个为最大分割次数



1 >>> '1,2,3'.split(',')
2 ['1', '2', '3']
3 >>> '1,2,3'.split(',', maxsplit=1)
4 ['1', '2,3']
5 >>> '1,2,,3,'.split(',')
6 ['1', '2', '', '3', '']
7
8 >>> '1 2 3'.split()
9 ['1', '2', '3']
10 >>> '1 2 3'.split(maxsplit=1)
11 ['1', '2 3']
12 >>> '   1   2   3   '.split()
13 ['1', '2', '3']
  
  0x06 lower, upper
  str.lower()把大写变为小写
  str.upper()把小写变为大写
  
  0x07 lstrip, rstrip, strip



str.strip()
  lstrip:把左边的字符去掉,rstrip:把右边的字符去掉,strip把子串中存在的字符去掉



#strip
>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
#lstrip
>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
#rstrip
>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
  
  0x08 maketrans & translate



str.maketrans(x[, y[, z]])
str.translate(map[, delchars])
  makestrans()创建对照表,然后使用translate函数根据对照表来把str中的字符进行相应的替换
  对于str.translate,简单说就是删除在str中的delchars,然后再按照map里面的字符映射关系映射



>>> s = 'abcdefg-123456'
#这里是把abc替换成ABC
>>> table = string.maketrans('abc', 'ABC')
>>> s.translate(table)
'ABCdefg-123456'
#这里是先把ab123删除掉,然后再进行替换
>>> s.translate(table, 'ab123')
'Cdefg-456'
>>>
  这里还有一个例子,pythonchallenge第一题



1 #!/usr/bin/env python
2
3 import string
4
5 tips = """
6 g fmnc wms bgblr rpylqjyrc gr zw fylb.
7 rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw
8 fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle.
9 sqgle qrpgle. kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.
10 """
11 alpha = string.lowercase
12 #这里对字母表进行映射,即把a替换成c
13 #abcdefghijklmnopqrstuvwxyz
14 #cdefghijklmnopqrstuvwxyzab
15 table = string.maketrans(alpha, alpha + alpha[:2])
16
17 print tips.translate(table)
18 #根据tips就可以得出结果
19 print "map".translate(table)
  
  0x09 replace



str.replace(old, new[, count])
  这个函数用来替换字符串,第三个参数可选,默认是全部替换,返回一个修改后的字符串,原字符串不变



1 >>> import string
2 >>> str = "hello hello"
3 >>> str.replace("hello", "hi")
4 'hi hi'
5 >>> str.replace("hello", "hi", 1)
6 'hi hello'
7 >>> print str
8 hello hello
  
  0x0a partition



str.partition(sep)
  这个方法也是用来分割字符串,和split不一样的是,它固定返回一个3元tuple,第一个是分隔符左边的内容,第二个是分隔符,第三个是分隔符右边的内容



1 >>> str = 'http://xxx.com/sss'
2 >>> str.partition("://")
3 ('http', '://', 'xxx.com/sss')
4 >>> str.split("://")
5 ['http', 'xxx.com/sss']
  partition其实是为了替换find,index而产生的,多数情况下需要用find找到一个位置,然后再进行分割,现在可以直接使用partition来进行分割



1 #!/usr/bin/env python
2 # coding=utf-8
3
4 import string
5 str = "http://www.baidu.com"
6
7 pos = str.find("://")
8 if pos:
9   print str[:pos], str
10
11 left, sep, right = str.partition("://")
12 print left, sep, right
  
  0x0b 判断字符串的一些方法



1 s为字符串
2 s.isalnum() 所有字符都是数字或者字母
3 s.isalpha() 所有字符都是字母
4 s.isdigit() 所有字符都是数字
5 s.islower() 所有字符都是小写
6 s.isupper() 所有字符都是大写
7 s.istitle() 所有单词都是首字母大写,像标题
8 s.isspace() 所有字符都是空白字符、 、、
9
10 判断是整数还是浮点数
11 a=123
12 b=123.123
13
14 >>>isinstance(a,int)
15 True
16 >>>isinstance(b,float)
17 True
18 >>>isinstance(b,int)
19 False
20
21 出处
22 http://wangwei007.blog.iyunv.com/68019/1108673
  
页: [1]
查看完整版本: Python String的一些方法