python str解析

Python的内建字符串类(无需import);它提供了很多常用的字符串处理函数。
str成员函数均不影响调用字符串本身,返回一个处理后的副本。

S.center(width[, fillchar]) -> string
以fillchar(必须是一个字符,默认为一空格)填充S到宽度为width,并以S居中。
类似的还有ljust,rjust

>>> s = "notice"
>>> s.rjust(20, '*')
'**************notice'
>>> s.ljust(20, '*')
'notice**************'
>>> s.center(20, '*')
'*******notice*******'

>>> s.center(20, "-*")
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    s.center(20, "-*")
TypeError: center() argument 2 must be char, not str
>>> s.center(1)
'notice'

S.lstrip([chars]) -> string or unicode
移除S开始部分中的由chars指定的字符,chars可以是多个字符(与center不同),默认是空白字符。
只要S开始的字符在参数chars中,即剔除,而不是整体和chars匹配才剔除。
如果chars是unicode,首先要将S转换为unicode,然后进行strip。
类似的有strip,rstrip

>>> s = string.whitespace
>>> s.lstrip()
''
>>> s = "ababcxyz"
>>> s.lstrip("abc")
'xyz'
>>> s
'ababcxyz'

S.endswith(suffix[, start[, end]]) -> bool
测试S[start:end]是不是以suffix结尾。
suffix也可以是由string组成的tuple,只要tuple中有一个元素通过测试则返回True。
类似的有startswith

>>> s = "This is a test."
>>> s.endswith("test.")
True
>>> test = ("test", "a test")
>>> s.endswith(test)
False
>>> test = ("test", "test.")
>>> s.endswith(test)
True

>>> s = "startswith"
>>> s.startswith("star")
True
>>> s.startswith("stat")
False
>>> slist = ("state", "spar")
>>> s.startswith(slist)
False
>>> slist = ("spar", "art")
>>> s.startswith(slist, 2)
True

S.count(sub[, start[, end]]) -> int
返回sub在S[start:end]中不重复出现的次数。

>>> s = "banana"
>>> s.count("an")
2
>>> s.count("ana")
1
>>> s.count("nan", -3)
0

S.find(sub [,start [,end]]) -> int
返回sub在S[start:end]中第一次出现的位置;查找失败返回-1(与index不同)。
类似的有rfind。

>>> s = "mississippi"
>>> s.rfind("ssi")
5
>>> s.find("ssi")
2
>>> s.find("mm")
-1
>>> s.rfind("mm")
-1

S.index(sub [,start [,end]]) -> int
同S.find(),除了:查找失败抛出ValueError。
类似的有rindex

>>> s = "This is a test."
>>> s.index("is")
2
>>> s.index("is", 3)
5
>>> s.index("is", 6)

Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    s.index("is", 6)
ValueError: substring not found

S.isalnum() -> bool
测试非空字符串中的字符是否要么是字母,要么是数字,即a~zA~Z0~9。
类似的有isalpha,isdigit,isspace,与islower,isupper不同的是,这些函数针对S中的每个字符测试,有一个不符即返回False

>>> import string
>>> all = string.letters + string.digits
>>> all
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
>>> all.isalnum()
True
>>> none = string.punctuation
>>> none
'!"#$%&/'()*+,-./:;<=>?@[//]^_`{|}~'
>>> none.isalnum()
False
>>> a = ""
>>> a.isalnum()
False
>>> a = "This is a test"
>>> a.isalnum()
False

S.isalpha() -> bool
测试非空字符串是否全是字母。

>>> a = "aB12"
>>> a.isalpha()
False
>>> a = "aB"
>>> a.isalpha()
True

S.isdigit() -> bool
测试非空字符串是否全是数字。

>>> "ab12".isdigit()
False
>>> "12".isdigit()
True
>>> "3.14".isdigit()
False

S.isspace() -> bool
测试非空字符串是否全是空白。

>>> import string
>>> string.whitespace
'/t/n/x0b/x0c/r '
>>> string.whitespace.isspace()
True
>>> "/t/t /n".isspace()
True
>>> " _ ".isspace()
False

S.islower() -> bool
测试非空字符串中可大小写转换的字母是否全是小写字母。
类似的还有isupper,lower,upper,swapcase,此类函数只测试可以大小写的字母,而忽略其他字符。

>>> "pi = 3.14".islower()
True
>>> "".islower()
False
>>> "PI = 3.14".islower()
False
>>> "PI = 3.14".isupper()
True
>>> s = "Beijing 2008"
>>> s.lower()
'beijing 2008'
>>> s.upper()
'BEIJING 2008'
>>> s
'Beijing 2008'

S.join(sequence) -> string
以S为分隔符链接sequence中的各个字符串
当len(sequence)<=1,返回值中不会出现S。

>>> s = ["this", "is", "Beijing"]
>>> "_*_".join(s)
'this_*_is_*_Beijing'
>>> "".join(s)
'thisisBeijing'

>>> " * ".join("1234")
'1 * 2 * 3 * 4'

>>> s = ["Beijing"]
>>> a.join(s)
'Beijing'
>>> s = []
>>> a.join(s)
''

S.split([sep [,maxsplit]]) -> list of strings
返回一个string组成的list:以sep(可以是字符串)为分隔符分割S,如果sep未指定,或者是None,则以空白为分隔符。
sep不会出现在返回值list中。sep左右一定存在一个元素体现在返回结果中。

>>> s = "Mississippi"
>>> s.split('s')
['Mi', '', 'i', '', 'ippi']
>>> s.split('ss')
['Mi', 'i', 'ippi']

>>> s = "1/t2/n/t3/n/t end"
>>> print s
1    2
    3
     end
>>> s.split()
['1', '2', '3', 'end']

>>> s = ""
>>> s.split("ss")
['']
>>> s = "hello"
>>> s.split()
['hello']

>>> s = "aaaaa"
>>> s.split("aa")
['', '', 'a']

>>> s = "onion"
>>> s.split("on")
['', 'i', '']

S.splitlines([keepends]) -> list of strings
返回S中各行组成的一个list。如果想在list的每个元素中包含换行符,需要设置keepends为True。

>>> s = "first/nsecond/nend"
>>> print s
first
second
end
>>> s.splitlines()
['first', 'second', 'end']
>>> s.splitlines(True)
['first/n', 'second/n', 'end']

>>> s = "/none line/n"
>>> s.splitlines()
['', 'one line']
>>> s.split("/n") #注意区别
['', 'one line', '']

S.partition(sep) -> (head, sep, tail)
以S中首次出现的sep为分隔符,分割S为三部分,并返回。
同类的还有rpartition。

>>> s = 'Mississippi'
>>> s.partition('ssi')
('Mi', 'ssi', 'ssippi')
>>> s.rpartition('ssi')
('Missi', 'ssi', 'ppi')

>>> s.partition("None")
('Mississippi', '', '')
>>> s.rpartition("None")
('', '', 'Mississippi')

S.replace (old, new[, count]) -> string
返回一副本:将S中的old全部替换为new。如果指定了count,则替换前count个。

>>> s = "_-_-_"
>>> s.replace("_", "**")
'**-**-**'
>>> s.replace("_", "**", 1)
'**-_-_'
>>> s
'_-_-_'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值