RUI个人博客 首页>>Python>>[原] Python 字符串string模块详解,string中所有的内建方法

[原] Python 字符串string模块详解,string中所有的内建方法

[原] Python 字符串string模块详解,string中所有的内建方法

本文是自己学习过程的一个整理的笔记,或许有一些不恰当的地方,如有遇到可以指出,大家一同讨论。

序列类型操作符
序列操作符 作用
seq [ind] 获得下表为ind的元素
seq [ind1:ind2] 获得下标从 ind1 到 ind2 间的元素集合
seq * expr 序列重复 expr 次
seq1 + seq2 连接序列 seq1 和 seq2
obj in seq 判断 obj 元素是否包含在 seq 中
obj not in seq 判断 obj 元素是否不包含在 seq 中

字符串类型内建方法:

string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.lowercase 'abcdefghijklmnopqrstuvwxyz'
string.uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits '0123456789'
string.hexdigits(十六进制) '0123456789abcdefABCDEF'
string.letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
string.octdigits(八进制) '01234567'
string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR
STUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
string.punctuation(标点符号) '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
string.whitespace(空白) '\t\n\x0b\x0c\r '
1. string.capitalize(s)
    把字符串的第一个字符大写
Python释义:
capitalize(s)
    capitalize(s) -> string
    
    Return a copy of the string s with only its first character
    capitalized.
示例:

>>> s
'foobar'
>>> string.capitalize(s)
'Foobar'
2. string.center(s, width[, fillchar])
   放回一个原字符串居中,并使用空格([,fillchar])填充至长度width 的新字符串
Python释义:
center(s, width, *args)
    center(s, width[, fillchar]) -> string
    
    Return a center version of s, in a field of the specified
    width. padded with spaces as needed. The string is never
    truncated. If specified the fillchar is used instead of spaces.
示例:

>>> s
'foobar'
>>> string.center(s,50,'=')
'======================foobar======================'
3. string.count(str,beg=0,end=len(string))
    返回str 在string 里面出现的次数,如果 beg 或者 end指定则返回指定范围内 str 出现的次数
Python释义:
count(s, *args)
    count(s, sub[, start[,end]]) -> int
    
    Return the number of occurrences of substring sub in string
    s[start:end]. Optional arguments start and end are
    interpreted as in slice notation.
示例:

>>> s
'I am tyger,I love Python'
>>> 
>>> string.count(s,'ov')
1
>>> string.count(s,'y')
2

4. string.decode(encoding='UTF-8' errors='strict')

    以dcoding 指定的编码格式解码 string,如果出错默认报一个 ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'
Python释义:

python 2.7.10 里面已成内建函数,具体见:
http://www.5ibig.com/article/index/arcid/62.htm

5. string.encode(encoding='UTF-8' errors='strict')
    以encoding 指定的编码格式编码 string,如果出错默认报一个 ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'
Python释义:
6. string.endswith(obj,beg=0,end=len(string))
    检查 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,
    如果是返回开始的索引值,则返回 -1
Python释义:
7. string.expandtabs(tabsize=8)
    把 字符串 string 中的 tab 符号转为空格,默认的空格数 tabsize 是 8
Python释义:
expandtabs(s, tabsize=8)
    expandtabs(s [,tabsize]) -> string
   
    Return a copy of the string s with all tab characters replaced
    by the appropriate number of spaces, depending on the current
    column, and the tabsize (default 8).
示例:

>>> s
'I am tyger,I love Python'
>>> string.expandtabs(s)
'I am tyger,I love Python'

8. string.find(str,beg=0,end=len(string))

    检查 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,
    如果是返回开始的索引值,否则返回 -1
Python释义:
find(s, *args) 
    find(s, sub [,start [,end]]) -> in
   
    Return the lowest index in s where substring sub is found,
    such that sub is contained within s[start,end]. Optional
    arguments start and end are interpreted as in slice notation.
   
    Return -1 on failure.
示例:

>>> s
'I am tyger,I love Python'
>>> string.find(s,'ove')
14
>>> string.find(s,'y')
6
>>> string.find(s,'y',7,len(s))
19
>>> 
>>> string.find(s,'yy')
-1

9. string.index(str,beg=0,end=len(string))

    跟 find() 方法一样,只不过如果 str 不在 string 中会报一个异常
Python释义:
index(s, *args)
    index(s, sub [,start [,end]]) -> int
   
    Like find but raises ValueError when the substring is not found.
示例:

>>> s
'I am tyger,I love Python'
>>> string.index(s,'ov')
14
>>> string.index(s,'yy')
Traceback (most recent call last):
  File "", line 1, in
  File "/usr/local/lib/python2.7/string.py", line 330, in index
    return s.index(*args)
ValueError: substring not found

10. string.isalnum()

    如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
Python释义:
11. string.isalpha()
    如果 string 至少有一个字符并且所有的字符都是字母则返回 True,否则返回 False
Python释义:
12. string.isdecimal()
    如果 string 只包含十进制数字则返回 True,否则返回 False
Python释义:
13. string.isdigit()
    如果 string 只包含数字则返回 True,否则返回 False
Python释义:
14. string.islower()
    如果 string 中包含至少一个区分大小写的字符,
    并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
Python释义:
15. string.isnumeric()
    如果 string 中只包含数字字符,则返回 True,否则返回 False
Python释义:
16. string.isspace()
    如果 string 中只包含空格,则返回 True,否则返回 False
Python释义:
17. string.istitle()
    如果 string 是标题化的(见 title()) 则返回 True,否则返回 False
Python释义:
18. string.isupper()
    如果 string 中包含至少一个区分大小写的字符,
    并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
Python释义:
19. string.join(seq)
    以 string 作为分隔符,将 seq 中所有的元素(字符串表示)合并为一个新的字符串
Python释义:
join(words, sep=' ')
    join(list [,sep]) -> string
   
    Return a string composed of the words in list, with
    intervening occurrences of sep. The default separator is a
    single space.
   
    (joinfields and join are synonymous)
示例:

>>> s
'I am tyger,I love Python'
>>> s2
'_'
>>> s.join(s2)
'_'
>>> s2.join(s)
'I_ _a_m_ _t_y_g_e_r_,_I_ _l_o_v_e_ _P_y_t_h_o_n'

20. string.ljust(width)

    返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
Python释义:
ljust(s, width, *args)
    ljust(s, width[, fillchar]) -> string
   
    Return a left-justified version of s, in a field of the
    specified width, padded with spaces as needed. The string is
    never truncated. If specified the fillchar is used instead of spaces.
示例:

>>> s
'I am tyger,I love Python'
>>> s.ljust(30)
'I am tyger,I love Python '
>>> s.ljust(30,'=')
'I am tyger,I love Python======'

21. string.lower()

    转换 string 中所有的大写字符为小写
Python释义:
lower(s)
    lower(s) -> string
   
    Return a copy of the string s converted to lowercase.
示例:

>>> s
'I am tyger,I love Python'
>>> s.lower()
'i am tyger,i love python'

22. string.lstrip()

    截掉 string 左边的空格
Python释义:
lstrip(s, chars=None)
    lstrip(s [,chars]) -> string
   
    Return a copy of the string s with leading whitespace removed.
    If chars is given and not None, remove characters in chars instead.
示例:

>>> s
' I am tyger,I love Python'
>>> s.lstrip()
'I am tyger,I love Python'

23. string.partition(str)

    有点像 find() 或 split() 的结合体,从 str 出现的第一个位置起,把字符串 string 分成
    一个 3 元组(string_pre_str,str,string_post_str),如果 string 中不包含 str 则 string_pre_str == string
Python释义:
24. string.replace(str1,str2,num=string count(str1))
    把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次
Python释义:
replace(s, old, new, maxreplace=-1)
    replace (str, old, new[, maxreplace]) -> string
   
    Return a copy of string str with all occurrences of substring
    old replaced by new. If the optional argument maxreplace is
    given, only the first maxreplace occurrences are replaced.
示例:

>>> s
' I am tyger,I love Python'
>>> s.replace(' ','_')
'___I_am_tyger,I_love_Python'
>>> 
>>> s.replace(' ','_',1)
'_ I am tyger,I love Python'
>>> s.replace(' ','_',-1)
'___I_am_tyger,I_love_Python'
>>> s.replace(' ','_',3)
'___I am tyger,I love Python'

25. string.rfind(str,beg=0,end=len(string))

    类似于 find() 函数,不过是从右边开始查找
Python释义:
rfind(s, *args)
    rfind(s, sub [,start [,end]]) -> int
   
    Return the highest index in s where substring sub is found,
    such that sub is contained within s[start,end]. Optional
    arguments start and end are interpreted as in slice notation.
   
    Return -1 on failure.
示例:

>>> s
' I am tyger,I love Python'
>>> s.rfind('y')
20
>>> s.find('y')
7
>>> s.rfind('yy')
-1

26. string.rindex(str,beg=0,end=len(string))

    类似于 index()函数,不过是从右边开始
Python释义:
rindex(s, *args)
    rindex(s, sub [,start [,end]]) -> int
   
    Like rfind but raises ValueError when the substring is not found.
示例:
>>> s
' I am tyger,I love Python'
>>> s.rindex('ov')
15
>>> s.index('ov')
15
>>> s.rindex('y')
20
>>> s.index('y')
7
>>> s.rindex('yy')
Traceback (most recent call last):
  File "", line 1, in
ValueError: substring not found
27. string.rjust(width)
    返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
Python释义:
rjust(s, width, *args)
    rjust(s, width[, fillchar]) -> string
   
    Return a right-justified version of s, in a field of the
    specified width, padded with spaces as needed. The string is
    never truncated. If specified the fillchar is used instead of spaces.
示例:
>>> s
' I am tyger,I love Python'
>>> s.rjust(30)
' I am tyger,I love Python'
>>> s.rjust(30,'=')
'===== I am tyger,I love Python'
28. string.rpartition(str)
    类似于 partition()函数,不过是从右边开始查找
Python释义:
29. string.rstrip()
    删除 string 字符串末尾的空格
Python释义:
rstrip(s, chars=None)
    rstrip(s [,chars]) -> string
   
    Return a copy of the string s with trailing whitespace removed.
    If chars is given and not None, remove characters in chars instead.
示例:
>>> s
' I am tyger,I love Python '
>>> s.lstrip()
'I am tyger,I love Python '
>>> s.rstrip()
' I am tyger,I love Python'
30. string.split(str="",num=string.count(str))
    以 str 为分隔符切片 string,如果 num 有指定值,则仅分隔 num个子字符串(结果为 num+1 子字符串)
Python释义:
split(s, sep=None, maxsplit=-1)
    split(s [,sep [,maxsplit]]) -> list of strings
   
    Return a list of the words in the string s, using sep as the
    delimiter string. If maxsplit is given, splits at no more than
    maxsplit places (resulting in at most maxsplit+1 words). If sep
    is not specified or is None, any whitespace string is a separator.
   
    (split and splitfields are synonymous)
示例:

>>> s
' I am tyger,I love Python '
>>> s.split(',')
[' I am tyger', 'I love Python ']
>>> s.split()
['I', 'am', 'tyger,I', 'love', 'Python']
>>> s.split(' ',3)
['', 'I', 'am', 'tyger,I love Python ']

31. string.rsplit()

    类似 split(),不过是从右边开始分隔
Python释义:
rsplit(s, sep=None, maxsplit=-1)
    rsplit(s [,sep [,maxsplit]]) -> list of strings
   
    Return a list of the words in the string s, using sep as the
    delimiter string, starting at the end of the string and working
    to the front. If maxsplit is given, at most maxsplit splits are
    done. If sep is not specified or is None, any whitespace string
    is a separator.
示例:

>>> s
' I am tyger,I love Python '
>>> s.rsplit(',')
[' I am tyger', 'I love Python ']
>>> s.rsplit()
['I', 'am', 'tyger,I', 'love', 'Python']
>>> s.rsplit(' ',3)
[' I am tyger,I love', 'Python', '', '']

32. string.splitlines(num=string.count('\n'))

    按照行分隔,返回一个包含各行作为元素的列表,则仅分隔 num 个子字符串
Python释义:
33. string.startswith(obj,beg=0,end=len(string))
    检查字符串是否是以 obj 开头,是则返回 True,否则返回 False,如果 beg 和 end 指定值,则在指定范围内检查
Python释义:
34. string.strip([obj])
    在 string 上执行 lstrip() 和 rstrip()
Python释义:
strip(s, chars=None)
    strip(s [,chars]) -> string
   
    Return a copy of the string s with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping.
示例:

>>> s
' I am tyger,I love Python '
>>> 
>>> s.strip()
'I am tyger,I love Python'
>>> s.lstrip()
'I am tyger,I love Python '
>>> s.rstrip()
' I am tyger,I love Python'

35. string.swapcase()

    翻转 string 中的大小写
Python释义:
swapcase(s)
    swapcase(s) -> string
   
    Return a copy of the string s with upper case characters
    converted to lowercase and vice versa.
示例:

>>> s
' I am tyger,I love Python '
>>> s.swapcase()
' i AM TYGER,i LOVE pYTHON '

36. string.title()

    返回"标题化"的 string,就是说所有单词都是以大写开始,其余字母均为小写(见istitle())
Python释义:
37. string.maketrans()

创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,
表示需要转换的字符,第二个参数也是字符串表示转换的目标
注:两个字符处你的长度必须相同,为一一对应的关系。否则报错!!!
Python释义:
maketrans(...)
    maketrans(frm, to) -> string
   
    Return a translation table (a string of 256 bytes long)
    suitable for use in string.translate. The strings frm and to
    must be of the same length.
示例:

>>> intab='I am tyger,'
>>> outtab='I love Python'
>>> trantab=string.maketrans(intab,outtab)
Traceback (most recent call last):
  File "", line 1, inValueError: maketrans arguments must have same length
>>> outtab='I love Pyth'
>>> trantab=string.maketrans(intab,outtab)
>>> trantab
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e
\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c
\x1d\x1e\x1fv!"#$%&\'()*+h-./0123456789:;
<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`lbcdyfPhijklonopqt
seuvwx z{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89
\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97
\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5
\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3
\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1
\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf
\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd
\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb
\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9
\xfa\xfb\xfc\xfd\xfe\xff'

>>> intab='amgr'
>>> outtab='1234'
>>> trantab=string.maketrans(intab,outtab)

38. string.translate(str,table,del="")

根据参数table 给出的表(包含 256 个字符) 转换 string 的字符,要过滤掉的字符放到 del 参数中
Python释义:
translate(s, table, deletions='')
    translate(s,table [,deletions]) -> string
   
    Return a copy of the string s, where all characters occurring
    in the optional argument deletions are removed, and the
    remaining characters have been mapped through the given
    translation table, which must be a string of length 256. The
    deletions argument is not allowed for Unicode strings.
示例:

>>> intab='amgr'
>>> outtab='1234'
>>> trantab=string.maketrans(intab,outtab)
>>> s
' I am tyger,I love Python '
>>> s.translate(trantab)
' I 12 ty3e4,I love Python '
>>> s.translate(trantab,'ove')
' I 12 ty34,I l Pythn '

39. string.upper()

转换 string 中的小写字母为大写
Python释义:
upper(s)
    upper(s) -> string
   
    Return a copy of the string s converted to uppercase.
示例:

>>> s
' I am tyger,I love Python '
>>> s.upper()
' I AM TYGER,I LOVE PYTHON '
>>> s.lower()
' i am tyger,i love python '

40. string.zfill(width)

返回长度为 width 的字符串,元字符串 string 右对齐,前面填充 0
Python释义:
zfill(x, width)
    zfill(x, width) -> string
   
    Pad a numeric string x with zeros on the left, to fill a field
    of the specified width. The string x is never truncated.
示例:

>>> s
' I am tyger,I love Python '
>>> s.zfill(30)
'000 I am tyger,I love Python '
>>> s.zfill(20)
' I am tyger,I love Python '

41. string.atof()

返回一个浮点值表示字符串 s
Python释义:
atof(s)
    atof(s) -> float
   
    Return the floating point number represented by the string s.
示例:

>>> string.atof(33)
33.0

42. string.atoi(str,base=10)

将字符串转换为整型数字,base 指定进制,默认为10进制
Python释义:
atoi(s, base=10)
    atoi(s [,base]) -> int
   
    Return the integer represented by the string s in the given
    base, which defaults to 10. The string s must consist of one
    or more digits, possibly preceded by a sign. If base is 0, it
    is chosen from the leading characters of s, 0 for octal, 0x or
    0X for hexadecimal. If base is 16, a preceding 0x or 0X is
    accepted.
示例:

>>> string.atoi('10')
10
>>> string.atoi('10',base=8)
8
>>> string.atoi('10',base=16)
16
>>> string.atoi('10',base=2)
2
>>> string.atoi('101',base=2)
5

43. string.atol(str,base=10)

将字符串转换为长整型数字,base 指定进制,默认为10进制
Python释义:
atol(s, base=10)
    atol(s [,base]) -> long
   
    Return the long integer represented by the string s in the
    given base, which defaults to 10. The string s must consist
    of one or more digits, possibly preceded by a sign. If base
    is 0, it is chosen from the leading characters of s, 0 for
    octal, 0x or 0X for hexadecimal. If base is 16, a preceding
    0x or 0X is accepted. A trailing L or l is not accepted,
    unless base is 0.
示例:
>>> string.atol('10')
10L
>>> string.atol('10',base=8)
8L
>>> string.atol('10',base=16)
16L
>>> string.atol('10',base=2)
2L
2016.11.30 于 北京邮储传    tyger.wang
昵  称:
邮  箱:
评论内容:
验 证 码:
可用[code][/code]插入代码
点击刷新验证码