day②:string内建方法

字符串内建方法:
string.expandtabs(tabsize=8) # tab符号转为空格 #默认8个空格
string.endswith(obj,beg=0,end=len(staring)) # 检测字符串是否已obj结束,如果是返回True #如果beg或end指定检测范围是否已obj结束
string.count(str,beg=0,end=len(string)) # 检测str在string里出现次数 f.count(' ',0,len(f)) 判断文件行数
string.find(str,beg=0,end=len(string)) # 检测str是否包含在string中
string.index(str,beg=0,end=len(string)) # 检测str不在string中,会报异常
string.isalnum() # 如果string至少有一个字符并且所有字符都是字母或数字则返回True
string.isalpha() # 如果string至少有一个字符并且所有字符都是字母则返回True
string.isnumeric() # 如果string只包含数字字符,则返回True
string.isspace() # 如果string包含空格则返回True
string.isupper() # 字符串都是大写返回True
string.islower() # 字符串都是小写返回True
string.lower() # 转换字符串中所有大写为小写
string.upper() # 转换字符串中所有小写为大写
string.lstrip() # 去掉string左边的空格
string.rstrip() # 去掉string字符末尾的空格
string.replace(str1,str2,num=string.count(str1)) # 把string中的str1替换成str2,如果num指定,则替换不超过num次
string.startswith(obj,beg=0,end=len(string)) # 检测字符串是否以obj开头
string.zfill(width) # 返回字符长度为width的字符,原字符串右对齐,前面填充0
string.isdigit() # 只包含数字返回True
string.split("分隔符") # 把string切片成一个列表
":".join(string.split()) # 以:作为分隔符,将所有元素合并为一个新的字符串

例子:
(1)capitalize
  1. def capitalize(self):
  2. """ 首字母变大写 """
  3. """
  4. S.capitalize() -> string
  5. Return a copy of the string S with only its first character
  6. capitalized.
  7. """
  8. return ""
  9. >>> name = 'yaobin'
  10. >>> name.capitalize()
  11. 'Yaobin'

(2)center
  1. def center(self, width, fillchar=None):
  2. """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
  3. """
  4. S.center(width[, fillchar]) -> string
  5. Return S centered in a string of length width. Padding is
  6. done using the specified fill character (default is a space)
  7. """
  8. return ""
  9. >>> name.center(20)
  10. ' yaobin '
  11. >>> name.center(20,"*")
  12. '*******yaobin*******'

(3)count
  1. def count(self, sub, start=None, end=None):
  2. """ 子序列个数 """
  3. """
  4. S.count(sub[, start[, end]]) -> int
  5. Return the number of non-overlapping occurrences of substring sub in
  6. string S[start:end]. Optional arguments start and end are interpreted
  7. as in slice notation.
  8. """
  9. return 0
  10. >>> name="yaobinyaobin"
  11. >>> name[0:1]
  12. 'y'
  13. >>> name.count('s')
  14. 0
  15. >>> name.count('y')
  16. 2
  17. >>> name.count('y',0,10)
  18. 2
  19. >>> name.count('y',0,5)
  20. 1

(4)expandtabs
  1. def expandtabs(self, tabsize=None):
  2. """ 将tab转换成空格,默认一个tab转换成8个空格 """
  3. """
  4. S.expandtabs([tabsize]) -> string
  5. Return a copy of S where all tab characters are expanded using spaces.
  6. If tabsize is not given, a tab size of 8 characters is assumed.
  7. """
  8. return ""
  9. >>> name = 'yao bin' #yao 和 bin之间有一个tab
  10. >>> name.expandtabs() #默认一个tab转化成8个空格
  11. 'yao bin'
  12. >>> name.expandtabs(1) #也可以自己指定多少个空格
  13. 'yao bin'
  14. >>> name.expandtabs(2)
  15. 'yao bin'
  16. >>> name.expandtabs(3)
  17. 'yao bin'
  18. >>> name.expandtabs(10)
  19. 'yao bin'
  20. >>> name.expandtabs(20)
  21. 'yao bin'

(5)find
  1. def find(self, sub, start=None, end=None):
  2. """ 寻找子序列位置,如果没找到,返回 -1 """
  3. """
  4. S.find(sub [,start [,end]]) -> int
  5. Return the lowest index in S where substring sub is found,
  6. such that sub is contained within S[start:end]. Optional
  7. arguments start and end are interpreted as in slice notation.
  8. Return -1 on failure.
  9. """
  10. return 0
  11. >>> name='yaobin'
  12. >>> name.find('n')
  13. 5
  14. >>> name.find('o')
  15. 2
  16. >>> name.find('no') #找不到返回-1
  17. -1
  18. >>>
  19. >>>
  20. >>> name='yaobinyaobin'
  21. >>> name.find('n') #默认找到第一个
  22. 5

(6)format
  1. def format(*args, **kwargs): # known special case of str.format
  2. """ 字符串格式化,动态参数,将函数式编程时细说 """
  3. """
  4. S.format(*args, **kwargs) -> string
  5. Return a formatted version of S, using substitutions from args and kwargs.
  6. The substitutions are identified by braces ('{' and '}').
  7. """
  8. pass
  9. >>> name="i m {0}, age {1}"
  10. >>> name
  11. 'i m {0}, age {1}'
  12. >>> name.format('yaobin',24) #按顺序的占位
  13. 'i m yaobin, age 24'
  14. >>> name="i m {0}, age {1}"
  15. >>> li = [2222,3333]
  16. >>> name.format(*li) #按顺序的占位,传一个列表进去,记得要加*
  17. 'i m 2222, age 3333'
  18. >>> name="i m {ss}, age {dd}"
  19. >>> name.format(ss='yaobin',dd=25)
  20. 'i m yaobin, age 25'
  21. >>> name.format(dd=25,ss='yaobin') #按名称的占位
  22. 'i m yaobin, age 25'
  23. >>> dic={'ss':123,'dd':456}
  24. >>> name
  25. 'i m {ss}, age {dd}'
  26. >>> name.format(**dic) #名称占位,传字典进去,记得加**
  27. 'i m 123, age 456'

(7)index
  1. def index(self, sub, start=None, end=None):
  2. """ 子序列位置,如果没找到,报错 """
  3. S.index(sub [,start [,end]]) -> int
  4. Like S.find() but raise ValueError when the substring is not found.
  5. """
  6. return 0
  7. >>> name = 'yaobin'
  8. >>> name.find('b')
  9. 3
  10. >>> name.index('b')
  11. 3
  12. >>> name.find('abc') #find找不到返回-1
  13. -1
  14. >>> name.index('abc') #index找不到,报错
  15. Traceback (most recent call last):
  16. File "<stdin>", line 1, in <module>
  17. ValueError: substring not found
  18. #注意和find的区别,find找不到,返回-1,而index找不到,报错

(8)isalnum
  1. def isalnum(self):
  2. """ 是否是字母和数字 """
  3. """
  4. S.isalnum() -> bool
  5. Return True if all characters in S are alphanumeric
  6. and there is at least one character in S, False otherwise.
  7. """
  8. return False
  9. >>> name
  10. 'yaobin'
  11. >>> name.isalnum()
  12. True
  13. >>> name = '你妹'
  14. >>> name.isalnum()
  15. False

(9)isalpha
  1. def isalpha(self):
  2. """ 是否是字母 """
  3. """
  4. S.isalpha() -> bool
  5. Return True if all characters in S are alphabetic
  6. and there is at least one character in S, False otherwise.
  7. """
  8. return False
  9. >>> name = 'yaobin'
  10. >>> name
  11. 'yaobin'
  12. >>> name.isalpha()
  13. True
  14. >>> name = 'yaobin234324'
  15. >>> name.isalpha()
  16. False
  17. >>> name = 'yaobin2'
  18. >>> name.isalpha()
  19. False
  20. >>> name = 'y2'
  21. >>> name.isalpha()
  22. False
  23. >>> name = '2'
  24. >>> name.isalpha()
  25. False
  26. >>> name = 'y'
  27. >>> name.isalpha()
  28. True

(10)isdigit
  1. def isdigit(self):
  2. """ 是否是数字 """
  3. """
  4. S.isdigit() -> bool
  5. Return True if all characters in S are digits
  6. and there is at least one character in S, False otherwise.
  7. """
  8. return False
  9. >>> name = 'yaobin'
  10. >>> name
  11. 'yaobin'
  12. >>> name.isdigit()
  13. False
  14. >>> name = '123'
  15. >>> name.isdigit()
  16. True

 (11)islower   
  1. def islower(self):
  2. """ 是否小写 """
  3. """
  4. S.islower() -> bool
  5. Return True if all cased characters in S are lowercase and there is
  6. at least one cased character in S, False otherwise.
  7. """
  8. return False
  9. >>> name ='yaobin'
  10. >>> name
  11. 'yaobin'
  12. >>> name.islower()
  13. True
  14. >>> name ='Yaobin'
  15. >>> name.islower()
  16. False
  17. >>> name ='234'
  18. >>> name.islower()
  19. False

(12)title、istitle
  1. def title(self):
  2. “”“转换成标题”“”
  3. """
  4. S.title() -> string
  5. Return a titlecased version of S, i.e. words start with uppercase
  6. characters, all remaining cased characters have lowercase.
  7. """
  8. return ""
  9. def istitle(self):
  10. “”“是否标题”“”
  11. """
  12. S.istitle() -> bool
  13. Return True if S is a titlecased string and there is at least one
  14. character in S, i.e. uppercase characters may only follow uncased
  15. characters and lowercase characters only cased ones. Return False
  16. otherwise.
  17. """
  18. return False
  19. >>> name = 'yaobin haha'
  20. >>> name
  21. 'yaobin haha'
  22. >>> name.title()
  23. 'Yaobin Haha' #转换成标题
  24. >>> name
  25. 'yaobin haha'
  26. >>> name.istitle() #判断是否标题
  27. False
  28. >>> name = 'Yaobin Haha'
  29. >>> name.istitle()
  30. True

(13)isupper
  1. def isupper(self):
  2. “”“是否大写”“”
  3. """
  4. S.isupper() -> bool
  5. Return True if all cased characters in S are uppercase and there is
  6. at least one cased character in S, False otherwise.
  7. """
  8. return False
  9. >>> name = 'Yaobin Haha'
  10. >>>
  11. >>> name.isupper()
  12. False
  13. >>> name = 'YAOBIN'
  14. >>> name.isupper()
  15. True

(14)join
  1. def join(self, iterable):
  2. """ 连接 """
  3. """
  4. S.join(iterable) -> string
  5. Return a string which is the concatenation of the strings in the
  6. iterable. The separator between elements is S.
  7. """
  8. return ""
  9. >>> li = ['s1','s2']
  10. >>> '_'.join(li)
  11. 's1_s2'

(15)lower、upper、swapcase
  1. def lower(self):
  2. """ 变小写 """
  3. """
  4. S.lower() -> string
  5. Return a copy of the string S converted to lowercase.
  6. """
  7. return ""
  8. def upper(self):
  9. “”“变大写”“”
  10. """
  11. S.upper() -> string
  12. Return a copy of the string S converted to uppercase.
  13. """
  14. return ""
  15. def swapcase(self):
  16. """ 大写变小写,小写变大写 """
  17. """
  18. S.swapcase() -> string
  19. Return a copy of the string S with uppercase characters
  20. converted to lowercase and vice versa.
  21. """
  22. return ""
  23. >>> name ="YAOBIN"
  24. >>> name.lower() #变大写
  25. 'yaobin'
  26. >>> name ="yaobin"
  27. >>> name.upper() #变大写
  28. 'YAOBIN'
  29. >>> name ="yaobin HAHA"
  30. >>> name.swapcase() #大写变小写,小写变大写
  31. 'YAOBIN haha'

(16)lstrip、rstrip、strip
  1. def lstrip(self, chars=None):
  2. """ 移除左侧空白 """
  3. """
  4. S.lstrip([chars]) -> string or unicode
  5. Return a copy of the string S with leading whitespace removed.
  6. If chars is given and not None, remove characters in chars instead.
  7. If chars is unicode, S will be converted to unicode before stripping
  8. """
  9. return ""
  10. def rstrip(self, chars=None):
  11. """ 移除右侧空白 """
  12. """
  13. S.rstrip([chars]) -> string or unicode
  14. Return a copy of the string S with trailing whitespace removed.
  15. If chars is given and not None, remove characters in chars instead.
  16. If chars is unicode, S will be converted to unicode before stripping
  17. """
  18. return ""
  19. def strip(self, chars=None):
  20. """ 移除两段空白 """
  21. """
  22. S.strip([chars]) -> string or unicode
  23. Return a copy of the string S with leading and trailing
  24. whitespace removed.
  25. If chars is given and not None, remove characters in chars instead.
  26. If chars is unicode, S will be converted to unicode before stripping
  27. """
  28. return ""
  29. >>> string01=" this my love "
  30. >>> string01.lstrip()
  31. 'this my love '
  32. >>> string01.rstrip()
  33. ' this my love'
  34. >>> string01.strip()
  35. 'this my love'

(17)partition
  1. def partition(self, sep):
  2. """ 分割,前,中,后三部分 """
  3. """
  4. S.partition(sep) -> (head, sep, tail)
  5. Search for the separator sep in S, and return the part before it,
  6. the separator itself, and the part after it. If the separator is not
  7. found, return S and two empty strings.
  8. """
  9. pass
  10. >>> name
  11. 'yaobin HAHA'
  12. >>> name.partition('in')
  13. ('yaob', 'in', ' HAHA')

(18)replace
  1. def replace(self, old, new, count=None):
  2. """ 替换 """
  3. """
  4. S.replace(old, new[, count]) -> string
  5. Return a copy of string S with all occurrences of substring
  6. old replaced by new. If the optional argument count is
  7. given, only the first count occurrences are replaced.
  8. """
  9. return ""
  10. >>> name
  11. 'yaobin HAHA'
  12. >>> name.replace('bin','biao')
  13. 'yaobiao HAHA'
  14. >>> name = 'yaobin yaobin yaobin'
  15. >>> name.replace('o','aaaaa') #会替换全部
  16. 'yaaaaaabin yaaaaaabin yaaaaaabin'

(19)split
  1. def split(self, sep=None, maxsplit=None):
  2. """ 分割, maxsplit最多分割几次 """
  3. """
  4. S.split([sep [,maxsplit]]) -> list of strings
  5. Return a list of the words in the string S, using sep as the
  6. delimiter string. If maxsplit is given, at most maxsplit
  7. splits are done. If sep is not specified or is None, any
  8. whitespace string is a separator and empty strings are removed
  9. from the result.
  10. """
  11. return []
  12. >>> name
  13. 'thisis a python script'
  14. >>> name.split()
  15. ['thisis', 'a', 'python', 'script']

(20)startswith、endswith
  1. def startswith(self, prefix, start=None, end=None):
  2. """ 是否起始 """
  3. """
  4. S.startswith(prefix[, start[, end]]) -> bool
  5. Return True if S starts with the specified prefix, False otherwise.
  6. With optional start, test S beginning at that position.
  7. With optional end, stop comparing S at that position.
  8. prefix can also be a tuple of strings to try.
  9. """
  10. return False
  11. def endswith(self, suffix, start=None, end=None):
  12. """ 是否以 xxx 结束 """
  13. """
  14. S.endswith(suffix[, start[, end]]) -> bool
  15. Return True if S ends with the specified suffix, False otherwise.
  16. With optional start, test S beginning at that position.
  17. With optional end, stop comparing S at that position.
  18. suffix can also be a tuple of strings to try.
  19. """
  20. return False
  21. >>> name = "my name is yaobin"
  22. >>> name.startswith('my')
  23. True
  24. >>> name.startswith('dfdfdfdfd')
  25. False
  26. >>> name.endswith('yaobin')
  27. True
  28. >>> name.endswith('yao')
  29. False

(21)zfill
  1. def zfill(self, width):
  2. """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
  3. """
  4. S.zfill(width) -> string
  5. Pad a numeric string S with zeros on the left, to fill a field
  6. of the specified width. The string S is never truncated.
  7. """
  8. return ""
  9. >>> name.zfill(1)
  10. 'my name is yaobin'
  11. >>> name.zfill(2)
  12. 'my name is yaobin'
  13. >>> name.zfill(17)
  14. 'my name is yaobin'
  15. >>> name.zfill(18)
  16. '0my name is yaobin'
  17. >>> name.zfill(19)
  18. '00my name is yaobin'
  19. >>> name.zfill(20)
  20. '000my name is yaobin'

(22)ljust、rjust
  1. def ljust(self, width, fillchar=None):
  2. """ 内容左对齐,右侧填充 """
  3. """
  4. S.ljust(width[, fillchar]) -> string
  5. Return S left-justified in a string of length width. Padding is
  6. done using the specified fill character (default is a space).
  7. """
  8. return ""
  9. def rjust(self, width, fillchar=None):
  10. """ 内容右对齐,左侧填充 """
  11. """
  12. S.rjust(width[, fillchar]) -> string
  13. Return S right-justified in a string of length width. Padding is
  14. done using the specified fill character (default is a space)
  15. """
  16. return ""
  17. >>> name ="yaobin hahah"
  18. >>> name.ljust(13,"=") #指定字符宽度
  19. 'yaobin hahah='
  20. >>> name.ljust(14,"=")
  21. 'yaobin hahah=='
  22. >>> name.ljust(15,"=")
  23. 'yaobin hahah==='
  24. >>> name.ljust(16,"=")
  25. 'yaobin hahah===='
  26. >>> name.ljust(17,"=")
  27. 'yaobin hahah====='
  28. >>> name.ljust(18,"=")
  29. 'yaobin hahah======'
  30. >>> name ="yaobin hahah"
  31. >>> name.rjust(13,"=") #指定字符宽度
  32. '=yaobin hahah'
  33. >>> name.rjust(15,"=")
  34. '===yaobin hahah'
  35. >>> name.rjust(16,"=")
  36. '====yaobin hahah'
  37. >>> name.rjust(17,"=")
  38. '=====yaobin hahah'
  39. >>> name.rjust(18,"=")
  40. '======yaobin hahah'

(23)translate
  1. def translate(self, table, deletechars=None):
  2. """
  3. 转换,需要先做一个对应表,deletechars表示删除字符集合
  4. >>> import string
  5. >>> intab = "aeiou"
  6. >>> outtab = "12345"
  7. >>> trantab = string.maketrans(intab, outtab)
  8. >>> str = "this is string example....wow!!!"
  9. >>> print str.translate(trantab, 'xm')
  10. th3s 3s str3ng 21pl2....w4w!!!
  11. """
  12. """
  13. S.translate(table [,deletechars]) -> string
  14. Return a copy of the string S, where all characters occurring
  15. in the optional argument deletechars are removed, and the
  16. remaining characters have been mapped through the given
  17. translation table, which must be a string of length 256 or None.
  18. If the table argument is None, no translation is applied and
  19. the operation simply removes the characters in deletechars.
  20. """
  21. return ""



end




原文地址:https://www.cnblogs.com/binhy0428/p/5125930.html