热线电话:13121318867

登录
首页精彩阅读python中string模块各属性以及函数的用法介绍
python中string模块各属性以及函数的用法介绍
2017-09-05
收藏

python中string模块各属性以及函数的用法介绍

下面小编就为大家带来一篇python中string模块各属性以及函数的用法介绍。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。

任何语言都离不开字符,那就会涉及对字符的操作,尤其是脚本语言更是频繁,不管是生产环境还是面试考验都要面对字符串的操作。

python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求:

python的字符串属性函数

python的string模块

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.字符串属性函数

系统版本:CentOS release 6.2 (Final)2.6.32-220.el6.x86_64

python版本:Python 2.6.6

字符串属性方法

字符串格式输出对齐
>>> str='stRINg lEArn' <br> <br>>>> <br> <br>>>> str.center(20)   #生成20个字符长度,str排中间 <br> <br>'  stRINg lEArn  ' <br> <br>>>>  <br> <br>>>> str.ljust(20)    #str左对齐 <br> <br>'stRINg lEArn    '  <br> <br>>>> <br> <br>>>> str.rjust(20)    #str右对齐 <br> <br>'    stRINg lEArn' <br> <br>>>>  <br> <br>>>> str.zfill(20)    #str右对齐,左边填充0 <br> <br>'00000000stRINg lEArn'

大小写转换    
>>> str='stRINg lEArn'  <br> <br>>>>  <br> <br>>>> str.upper() #转大写 <br> <br>'STRING LEARN' <br> <br>>>>  <br> <br>>>> str.lower() #转小写 <br> <br>'string learn' <br> <br>>>>  <br> <br>>>> str.capitalize() #字符串首为大写,其余小写 <br> <br>'String learn' <br> <br>>>>  <br> <br>>>> str.swapcase() #大小写对换 <br> <br>'STrinG LeaRN' <br> <br>>>>  <br> <br>>>> str.title() #以分隔符为标记,首字符为大写,其余为小写 <br> <br>'String Learn'

字符串条件判断
    
>>> str='0123'
 
>>> str.isalnum() #是否全是字母和数字,并至少有一个字符
True
 
>>> str.isdigit() #是否全是数字,并至少有一个字符
True
 
 
 
>>> str='abcd'
 
>>> str.isalnum()
 
True
 
>>> str.isalpha() #是否全是字母,并至少有一个字符
True
 
>>> str.islower() #是否全是小写,当全是小写和数字一起时候,也判断为True
True
 
 
 
>>> str='abcd0123'
 
>>> str.islower() #同上
 
True
 
>>> str.isalnum()  
 
True
 
 
 
>>> str=' '
 
>>> str.isspace() #是否全是空白字符,并至少有一个字符
True
 
>>> str='ABC'
 
>>> str.isupper() #是否全是大写,当全是大写和数字一起时候,也判断为True
True
 
>>> str='Abb Acc'
 
>>> str.istitle() #所有单词字首都是大写,标题
True
 
 
>>> str='string learn'
>>> str.startswith('str') #判断字符串以'str'开头
True
>>> str.endswith('arn') #判读字符串以'arn'结尾
True

字符串搜索定位与替换
    
>>> str='string lEARn'
 
>>>
 
>>> str.find('a')  #查找字符串,没有则返回-1,有则返回查到到第一个匹配的索引
 
-1
 
>>> str.find('n')
 
4
 
>>> str.rfind('n')  #同上,只是返回的索引是最后一次匹配的
 
11
 
>>>
 
>>> str.index('a')  #如果没有匹配则报错
 
Traceback (most recent call last):
 
 File "<stdin>", line 1, in <module>
 
ValueError: substring not found
 
>>> str.index('n')  #同find类似,返回第一次匹配的索引值
 
4
 
>>> str.rindex('n') #返回最后一次匹配的索引值
 
11
 
>>>
 
>>> str.count('a')  #字符串中匹配的次数
 
0
 
>>> str.count('n')  #同上
 
2
 
>>>
 
>>> str.replace('EAR','ear') #匹配替换
 
'string learn'
 
>>> str.replace('n','N')
 
'striNg lEARN'
 
>>> str.replace('n','N',1)
 
'striNg lEARn'
 
>>>
 
>>>
 
>>> str.strip('n') #删除字符串首尾匹配的字符,通常用于默认删除回车符
 
'string lEAR'
 
>>> str.lstrip('n') #左匹配
 
'string lEARn'
 
>>> str.rstrip('n') #右匹配
 
'string lEAR'
 
>>>
 
>>> str=' tab'
 
>>> str.expandtabs() #把制表符转为空格
 
'  tab'
 
>>> str.expandtabs(2) #指定空格数
 
' tab'

字符串编码与解码    
>>> str='字符串学习'
 
>>> str
 
'xe5xadx97xe7xacxa6xe4xb8xb2xe5xadxa6xe4xb9xa0'
 
>>>
 
>>> str.decode('utf-8')    #解码过程,将utf-8解码为unicode
 
u'u5b57u7b26u4e32u5b66u4e60'
 
 
 
>>> str.decode('utf-8').encode('gbk') #编码过程,将unicode编码为gbk
 
'xd7xd6xb7xfbxb4xaexd1xa7xcfxb0'
 
>>> str.decode('utf-8').encode('utf-8') #将unicode编码为utf-8
 
'xe5xadx97xe7xacxa6xe4xb8xb2xe5xadxa6xe4xb9xa0'

字符串分割变换1
    
>>> str='Learn string'
 
>>> '-'.join(str)
 
'L-e-a-r-n- -s-t-r-i-n-g'
 
>>> l1=['Learn','string']
 
>>> '-'.join(l1)
 
'Learn-string'
 
>>>
 
>>> str.split('n')
 
['Lear', ' stri', 'g']
 
>>> str.split('n',1)
 
['Lear', ' string']
 
>>> str.rsplit('n',1)
 
['Learn stri', 'g']
 
>>>
 
>>> str.splitlines()
 
['Learn string']
 
>>>
 
>>> str.partition('n')
 
('Lear', 'n', ' string')
 
>>> str.rpartition('n')
 
('Learn stri', 'n', 'g')

string模块源代码
?
1
    
"""A collection of string operations (most are no longer used). <br> <br> <br>Warning: most of the code you see here isn't normally used nowadays. <br> <br>Beginning with Python 1.6, many of these functions are implemented as <br> <br>methods on the standard string object. They used to be implemented by <br> <br>a built-in module called strop, but strop is now obsolete itself. <br> <br> <br>Public module variables: <br> <br> <br>whitespace -- a string containing all characters considered whitespace <br> <br>lowercase -- a string containing all characters considered lowercase letters <br> <br>uppercase -- a string containing all characters considered uppercase letters <br> <br>letters -- a string containing all characters considered letters <br> <br>digits -- a string containing all characters considered decimal digits <br> <br>hexdigits -- a string containing all characters considered hexadecimal digits <br> <br>octdigits -- a string containing all characters considered octal digits <br> <br>punctuation -- a string containing all characters considered punctuation <br> <br>printable -- a string containing all characters considered printable <br> <br> <br>""" <br> <br> <br># Some strings for ctype-style character classification <br> <br>whitespace = ' tnrvf' <br> <br>lowercase = 'abcdefghijklmnopqrstuvwxyz' <br> <br>uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' <br> <br>letters = lowercase + uppercase <br> <br>ascii_lowercase = lowercase <br> <br>ascii_uppercase = uppercase <br> <br>ascii_letters = ascii_lowercase + ascii_uppercase <br> <br>digits = '0123456789' <br> <br>hexdigits = digits + 'abcdef' + 'ABCDEF' <br> <br>octdigits = '01234567' <br> <br>punctuation = """!"#$%&'()*+,-./:;<=>?@[]^_`{|}~""" <br> <br>printable = digits + letters + punctuation + whitespace <br> <br> <br> <br># Case conversion helpers <br> <br># Use str to convert Unicode literal in case of -U <br> <br>l = map(chr, xrange(256)) <br> <br>_idmap = str('').join(l) <br> <br>del l <br> <br> <br> <br># Functions which aren't available as string methods. <br> <br> <br> <br># Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def". <br> <br>def capwords(s, sep=None): <br> <br>  """capwords(s [,sep]) -> string <br> <br> <br>  Split the argument into words using split, capitalize each <br> <br>  word using capitalize, and join the capitalized words using <br> <br>  join. If the optional second argument sep is absent or None, <br> <br>  runs of whitespace characters are replaced by a single space <br> <br>  and leading and trailing whitespace are removed, otherwise <br> <br>  sep is used to split and join the words. <br> <br> <br>  """ <br> <br>  return (sep or ' ').join(x.capitalize() for x in s.split(sep)) <br> <br> <br># Construct a translation string <br> <br>_idmapL = None <br> <br>def maketrans(fromstr, tostr): <br> <br>  """maketrans(frm, to) -> string <br> <br> <br>  Return a translation table (a string of 256 bytes long) <br> <br>  suitable for use in string.translate. The strings frm and to <br> <br>  must be of the same length. <br> <br> <br>  """ <br> <br>  if len(fromstr) != len(tostr): <br> <br>    raise ValueError, "maketrans arguments must have same length" <br> <br>  global _idmapL <br> <br>  if not _idmapL: <br> <br>    _idmapL = list(_idmap) <br> <br>  L = _idmapL[:] <br> <br>  fromstr = map(ord, fromstr) <br> <br>  for i in range(len(fromstr)): <br> <br>    L[fromstr[i]] = tostr[i] <br> <br>  return ''.join(L) <br> <br> <br> <br>#################################################################### <br> <br>import re as _re <br> <br> <br>class _multimap: <br> <br>  """Helper class for combining multiple mappings. <br> <br> <br> <br>  Used by .{safe_,}substitute() to combine the mapping and keyword <br> <br>  arguments. <br> <br>  """ <br> <br>  def __init__(self, primary, secondary): <br> <br>    self._primary = primary <br> <br>    self._secondary = secondary <br> <br> <br> <br>  def __getitem__(self, key): <br> <br>    try: <br> <br>      return self._primary[key] <br> <br>    except KeyError: <br> <br>      return self._secondary[key] <br> <br> <br> <br>class _TemplateMetaclass(type): <br> <br>  pattern = r""" <br> <br>  %(delim)s(?: <br> <br>   (?P<escaped>%(delim)s) | # Escape sequence of two delimiters <br> <br>   (?P<named>%(id)s) | # delimiter and a Python identifier <br> <br>   {(?P<braced>%(id)s)} | # delimiter and a braced identifier <br> <br>   (?P<invalid>) # Other ill-formed delimiter exprs <br> <br>  ) <br> <br>  """ <br> <br> <br>  def __init__(cls, name, bases, dct): <br> <br>    super(_TemplateMetaclass, cls).__init__(name, bases, dct) <br> <br>    if 'pattern' in dct: <br> <br>      pattern = cls.pattern <br> <br>    else: <br> <br>      pattern = _TemplateMetaclass.pattern % { <br> <br>        'delim' : _re.escape(cls.delimiter), <br> <br>        'id' : cls.idpattern, <br> <br>        } <br> <br>    cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) <br> <br> <br> <br>class Template: <br> <br>  """A string class for supporting $-substitutions.""" <br> <br>  __metaclass__ = _TemplateMetaclass <br> <br> <br> <br>  delimiter = '$' <br> <br>  idpattern = r'[_a-z][_a-z0-9]*' <br> <br> <br> <br>  def __init__(self, template): <br> <br>    self.template = template <br> <br> <br> <br>  # Search for $$, $identifier, ${identifier}, and any bare $'s <br> <br> <br> <br>  def _invalid(self, mo): <br> <br>    i = mo.start('invalid') <br> <br>    lines = self.template[:i].splitlines(True) <br> <br>    if not lines: <br> <br>      colno = 1 <br> <br>      lineno = 1 <br> <br>    else: <br> <br>      colno = i - len(''.join(lines[:-1])) <br> <br>      lineno = len(lines) <br> <br>    raise ValueError('Invalid placeholder in string: line %d, col %d' % <br> <br>             (lineno, colno)) <br> <br> <br> <br>  def substitute(self, *args, **kws): <br> <br>    if len(args) > 1: <br> <br>      raise TypeError('Too many positional arguments') <br> <br>    if not args: <br> <br>      mapping = kws <br> <br>    elif kws: <br> <br>      mapping = _multimap(kws, args[0]) <br> <br>    else: <br> <br>      mapping = args[0] <br> <br>    # Helper function for .sub() <br> <br>    def convert(mo): <br> <br>      # Check the most common path first. <br> <br>      named = mo.group('named') or mo.group('braced') <br> <br>      if named is not None: <br> <br>        val = mapping[named] <br> <br>        # We use this idiom instead of str() because the latter will <br> <br>        # fail if val is a Unicode containing non-ASCII characters. <br> <br>        return '%s' % (val,) <br> <br>      if mo.group('escaped') is not None: <br> <br>        return self.delimiter <br> <br>      if mo.group('invalid') is not None: <br> <br>        self._invalid(mo) <br> <br>      raise ValueError('Unrecognized named group in pattern', <br> <br>               self.pattern) <br> <br>    return self.pattern.sub(convert, self.template) <br> <br> <br> <br>  def safe_substitute(self, *args, **kws): <br> <br>    if len(args) > 1: <br> <br>      raise TypeError('Too many positional arguments') <br> <br>    if not args: <br> <br>      mapping = kws <br> <br>    elif kws: <br> <br>      mapping = _multimap(kws, args[0]) <br> <br>    else: <br> <br>      mapping = args[0] <br> <br>    # Helper function for .sub() <br> <br>    def convert(mo): <br> <br>      named = mo.group('named') <br> <br>      if named is not None: <br> <br>        try: <br> <br>          # We use this idiom instead of str() because the latter <br> <br>          # will fail if val is a Unicode containing non-ASCII <br> <br>          return '%s' % (mapping[named],) <br> <br>        except KeyError: <br> <br>          return self.delimiter + named <br> <br>      braced = mo.group('braced') <br> <br>      if braced is not None: <br> <br>        try: <br> <br>          return '%s' % (mapping[braced],) <br> <br>        except KeyError: <br> <br>          return self.delimiter + '{' + braced + '}' <br> <br>      if mo.group('escaped') is not None: <br> <br>        return self.delimiter <br> <br>      if mo.group('invalid') is not None: <br> <br>        return self.delimiter <br> <br>      raise ValueError('Unrecognized named group in pattern', <br> <br>               self.pattern) <br> <br>    return self.pattern.sub(convert, self.template) <br> <br> <br> <br> <br> <br> <br> <br>#################################################################### <br> <br># NOTE: Everything below here is deprecated. Use string methods instead. <br> <br># This stuff will go away in Python 3.0. <br> <br> <br> <br># Backward compatible names for exceptions <br> <br>index_error = ValueError <br> <br>atoi_error = ValueError <br> <br>atof_error = ValueError <br> <br>atol_error = ValueError <br> <br> <br> <br># convert UPPER CASE letters to lower case <br> <br>def lower(s): <br> <br>  """lower(s) -> string <br> <br> <br> <br>  Return a copy of the string s converted to lowercase. <br> <br> <br> <br>  """ <br> <br>  return s.lower() <br> <br> <br> <br># Convert lower case letters to UPPER CASE <br> <br>def upper(s): <br> <br>  """upper(s) -> string <br> <br> <br> <br>  Return a copy of the string s converted to uppercase. <br> <br> <br> <br>  """ <br> <br>  return s.upper() <br> <br> <br> <br># Swap lower case letters and UPPER CASE <br> <br>def swapcase(s): <br> <br>  """swapcase(s) -> string <br> <br> <br> <br>  Return a copy of the string s with upper case characters <br> <br>  converted to lowercase and vice versa. <br> <br> <br> <br>  """ <br> <br>  return s.swapcase() <br> <br> <br> <br># Strip leading and trailing tabs and spaces <br> <br>def strip(s, chars=None): <br> <br>  """strip(s [,chars]) -> string <br> <br> <br> <br>  Return a copy of the string s with leading and trailing <br> <br>  whitespace removed. <br> <br>  If chars is given and not None, remove characters in chars instead. <br> <br>  If chars is unicode, S will be converted to unicode before stripping. <br> <br> <br> <br>  """ <br> <br>  return s.strip(chars) <br> <br> <br> <br># Strip leading tabs and spaces <br> <br>def lstrip(s, chars=None): <br> <br>  """lstrip(s [,chars]) -> string <br> <br> <br> <br>  Return a copy of the string s with leading whitespace removed. <br> <br>  If chars is given and not None, remove characters in chars instead. <br> <br> <br> <br>  """ <br> <br>  return s.lstrip(chars) <br> <br> <br> <br># Strip trailing tabs and spaces <br> <br>def rstrip(s, chars=None): <br> <br>  """rstrip(s [,chars]) -> string <br> <br> <br> <br>  Return a copy of the string s with trailing whitespace removed. <br> <br>  If chars is given and not None, remove characters in chars instead. <br> <br> <br> <br>  """ <br> <br>  return s.rstrip(chars) <br> <br> <br> <br> <br> <br># Split a string into a list of space/tab-separated words <br> <br>def split(s, sep=None, maxsplit=-1): <br> <br>  """split(s [,sep [,maxsplit]]) -> list of strings <br> <br> <br> <br>  Return a list of the words in the string s, using sep as the <br> <br>  delimiter string. If maxsplit is given, splits at no more than <br> <br>  maxsplit places (resulting in at most maxsplit+1 words). If sep <br> <br>  is not specified or is None, any whitespace string is a separator. <br> <br> <br> <br>  (split and splitfields are synonymous) <br> <br> <br> <br>  """ <br> <br>  return s.split(sep, maxsplit) <br> <br>splitfields = split <br> <br> <br> <br># Split a string into a list of space/tab-separated words <br> <br>def rsplit(s, sep=None, maxsplit=-1): <br> <br>  """rsplit(s [,sep [,maxsplit]]) -> list of strings <br> <br> <br> <br>  Return a list of the words in the string s, using sep as the <br> <br>  delimiter string, starting at the end of the string and working <br> <br>  to the front. If maxsplit is given, at most maxsplit splits are <br> <br>  done. If sep is not specified or is None, any whitespace string <br> <br>  is a separator. <br> <br>  """ <br> <br>  return s.rsplit(sep, maxsplit) <br> <br> <br> <br># Join fields with optional separator <br> <br>def join(words, sep = ' '): <br> <br>  """join(list [,sep]) -> string <br> <br> <br> <br>  Return a string composed of the words in list, with <br> <br>  intervening occurrences of sep. The default separator is a <br> <br>  single space. <br> <br> <br> <br>  (joinfields and join are synonymous) <br> <br> <br> <br>  """ <br> <br>  return sep.join(words) <br> <br>joinfields = join <br> <br> <br> <br># Find substring, raise exception if not found <br> <br>def index(s, *args): <br> <br>  """index(s, sub [,start [,end]]) -> int <br> <br> <br> <br>  Like find but raises ValueError when the substring is not found. <br> <br> <br> <br>  """ <br> <br>  return s.index(*args) <br> <br> <br> <br># Find last substring, raise exception if not found <br> <br>def rindex(s, *args): <br> <br>  """rindex(s, sub [,start [,end]]) -> int <br> <br> <br> <br>  Like rfind but raises ValueError when the substring is not found. <br> <br> <br> <br>  """ <br> <br>  return s.rindex(*args) <br> <br> <br> <br># Count non-overlapping occurrences of substring <br> <br>def count(s, *args): <br> <br>  """count(s, sub[, start[,end]]) -> int <br> <br> <br> <br>  Return the number of occurrences of substring sub in string <br> <br>  s[start:end]. Optional arguments start and end are <br> <br>  interpreted as in slice notation. <br> <br> <br> <br>  """ <br> <br>  return s.count(*args) <br> <br> <br> <br># Find substring, return -1 if not found <br> <br>def find(s, *args): <br> <br>  """find(s, sub [,start [,end]]) -> in <br> <br> <br> <br>  Return the lowest index in s where substring sub is found, <br> <br>  such that sub is contained within s[start,end]. Optional <br> <br>  arguments start and end are interpreted as in slice notation. <br> <br> <br> <br>  Return -1 on failure. <br> <br> <br> <br>  """ <br> <br>  return s.find(*args) <br> <br> <br> <br># Find last substring, return -1 if not found <br> <br>def rfind(s, *args): <br> <br>  """rfind(s, sub [,start [,end]]) -> int <br> <br> <br> <br>  Return the highest index in s where substring sub is found, <br> <br>  such that sub is contained within s[start,end]. Optional <br> <br>  arguments start and end are interpreted as in slice notation. <br> <br> <br> <br>  Return -1 on failure. <br> <br> <br> <br>  """ <br> <br>  return s.rfind(*args) <br> <br> <br> <br># for a bit of speed <br> <br>_float = float <br> <br>_int = int <br> <br>_long = long <br> <br> <br> <br># Convert string to float <br> <br>def atof(s): <br> <br>  """atof(s) -> float <br> <br> <br> <br>  Return the floating point number represented by the string s. <br> <br> <br> <br>  """ <br> <br>  return _float(s) <br> <br> <br> <br> <br> <br># Convert string to integer <br> <br>def atoi(s , base=10): <br> <br>  """atoi(s [,base]) -> int <br> <br> <br> <br>  Return the integer represented by the string s in the given <br> <br>  base, which defaults to 10. The string s must consist of one <br> <br>  or more digits, possibly preceded by a sign. If base is 0, it <br> <br>  is chosen from the leading characters of s, 0 for octal, 0x or <br> <br>  0X for hexadecimal. If base is 16, a preceding 0x or 0X is <br> <br>  accepted. <br> <br> <br> <br>  """ <br> <br>  return _int(s, base) <br> <br> <br> <br> <br> <br># Convert string to long integer <br> <br>def atol(s, base=10): <br> <br>  """atol(s [,base]) -> long <br> <br> <br> <br>  Return the long integer represented by the string s in the <br> <br>  given base, which defaults to 10. The string s must consist <br> <br>  of one or more digits, possibly preceded by a sign. If base <br> <br>  is 0, it is chosen from the leading characters of s, 0 for <br> <br>  octal, 0x or 0X for hexadecimal. If base is 16, a preceding <br> <br>  0x or 0X is accepted. A trailing L or l is not accepted, <br> <br>  unless base is 0. <br> <br> <br> <br>  """ <br> <br>  return _long(s, base) <br> <br> <br> <br> <br> <br># Left-justify a string <br> <br>def ljust(s, width, *args): <br> <br>  """ljust(s, width[, fillchar]) -> string <br> <br> <br> <br>  Return a left-justified version of s, in a field of the <br> <br>  specified width, padded with spaces as needed. The string is <br> <br>  never truncated. If specified the fillchar is used instead of spaces. <br> <br> <br> <br>  """ <br> <br>  return s.ljust(width, *args) <br> <br> <br> <br># Right-justify a string <br> <br>def rjust(s, width, *args): <br> <br>  """rjust(s, width[, fillchar]) -> string <br> <br> <br> <br>  Return a right-justified version of s, in a field of the <br> <br>  specified width, padded with spaces as needed. The string is <br> <br>  never truncated. If specified the fillchar is used instead of spaces. <br> <br> <br> <br>  """ <br> <br>  return s.rjust(width, *args) <br> <br> <br> <br># Center a string <br> <br>def center(s, width, *args): <br> <br>  """center(s, width[, fillchar]) -> string <br> <br> <br> <br>  Return a center version of s, in a field of the specified <br> <br>  width. padded with spaces as needed. The string is never <br> <br>  truncated. If specified the fillchar is used instead of spaces. <br> <br> <br> <br>  """ <br> <br>  return s.center(width, *args) <br> <br> <br> <br># Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03' <br> <br># Decadent feature: the argument may be a string or a number <br> <br># (Use of this is deprecated; it should be a string as with ljust c.s.) <br> <br>def zfill(x, width): <br> <br>  """zfill(x, width) -> string <br> <br> <br> <br>  Pad a numeric string x with zeros on the left, to fill a field <br> <br>  of the specified width. The string x is never truncated. <br> <br> <br> <br>  """ <br> <br>  if not isinstance(x, basestring): <br> <br>    x = repr(x) <br> <br>  return x.zfill(width) <br> <br> <br> <br># Expand tabs in a string. <br> <br># Doesn't take non-printing chars into account, but does understand n. <br> <br>def expandtabs(s, tabsize=8): <br> <br>  """expandtabs(s [,tabsize]) -> string <br> <br> <br> <br>  Return a copy of the string s with all tab characters replaced <br> <br>  by the appropriate number of spaces, depending on the current <br> <br>  column, and the tabsize (default 8). <br> <br> <br> <br>  """ <br> <br>  return s.expandtabs(tabsize) <br> <br> <br> <br># Character translation through look-up table. <br> <br>def translate(s, table, deletions=""): <br> <br>  """translate(s,table [,deletions]) -> string <br> <br> <br> <br>  Return a copy of the string s, where all characters occurring <br> <br>  in the optional argument deletions are removed, and the <br> <br>  remaining characters have been mapped through the given <br> <br>  translation table, which must be a string of length 256. The <br> <br>  deletions argument is not allowed for Unicode strings. <br> <br> <br> <br>  """ <br> <br>  if deletions or table is None: <br> <br>    return s.translate(table, deletions) <br> <br>  else: <br> <br>    # Add s[:0] so that if s is Unicode and table is an 8-bit string, <br> <br>    # table is converted to Unicode. This means that table *cannot* <br> <br>    # be a dictionary -- for that feature, use u.translate() directly. <br> <br>    return s.translate(table + s[:0]) <br> <br> <br> <br># Capitalize a string, e.g. "aBc dEf" -> "Abc def". <br> <br>def capitalize(s): <br> <br>  """capitalize(s) -> string <br> <br> <br> <br>  Return a copy of the string s with only its first character <br> <br>  capitalized. <br> <br> <br> <br>  """ <br> <br>  return s.capitalize() <br> <br> <br> <br># Substring replacement (global) <br> <br>def replace(s, old, new, maxsplit=-1): <br> <br>  """replace (str, old, new[, maxsplit]) -> string <br> <br> <br> <br>  Return a copy of string str with all occurrences of substring <br> <br>  old replaced by new. If the optional argument maxsplit is <br> <br>  given, only the first maxsplit occurrences are replaced. <br> <br> <br> <br>  """ <br> <br>  return s.replace(old, new, maxsplit) <br> <br> <br> <br> <br> <br># Try importing optional built-in module "strop" -- if it exists, <br> <br># it redefines some string operations that are 100-1000 times faster. <br> <br># It also defines values for whitespace, lowercase and uppercase <br> <br># that match <ctype.h>'s definitions. <br> <br> <br> <br>try: <br> <br>  from strop import maketrans, lowercase, uppercase, whitespace <br> <br>  letters = lowercase + uppercase <br> <br>except ImportError: <br> <br>  pass # Use the original versions <br> <br> <br> <br>######################################################################## <br> <br># the Formatter class <br> <br># see PEP 3101 for details and purpose of this class <br> <br> <br> <br># The hard parts are reused from the C implementation. They're exposed as "_" <br> <br># prefixed methods of str and unicode. <br> <br> <br> <br># The overall parser is implemented in str._formatter_parser. <br> <br># The field name parser is implemented in str._formatter_field_name_split <br> <br> <br> <br>class Formatter(object): <br> <br>  def format(self, format_string, *args, **kwargs): <br> <br>    return self.vformat(format_string, args, kwargs) <br> <br> <br> <br>  def vformat(self, format_string, args, kwargs): <br> <br>    used_args = set() <br> <br>    result = self._vformat(format_string, args, kwargs, used_args, 2) <br> <br>    self.check_unused_args(used_args, args, kwargs) <br> <br>    return result <br> <br> <br> <br>  def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): <br> <br>    if recursion_depth < 0: <br> <br>      raise ValueError('Max string recursion exceeded') <br> <br>    result = [] <br> <br>    for literal_text, field_name, format_spec, conversion in  <br> <br>        self.parse(format_string): <br> <br> <br> <br>      # output the literal text <br> <br>      if literal_text: <br> <br>        result.append(literal_text) <br> <br> <br> <br>      # if there's a field, output it <br> <br>      if field_name is not None: <br> <br>        # this is some markup, find the object and do <br> <br>        # the formatting <br> <br> <br> <br>        # given the field_name, find the object it references <br> <br>        # and the argument it came from <br> <br>        obj, arg_used = self.get_field(field_name, args, kwargs) <br> <br>        used_args.add(arg_used) <br> <br> <br> <br>        # do any conversion on the resulting object <br> <br>        obj = self.convert_field(obj, conversion) <br> <br> <br> <br>        # expand the format spec, if needed <br> <br>        format_spec = self._vformat(format_spec, args, kwargs, <br> <br>                      used_args, recursion_depth-1) <br> <br> <br> <br>        # format the object and append to the result <br> <br>        result.append(self.format_field(obj, format_spec)) <br> <br> <br> <br>    return ''.join(result) <br> <br> <br> <br> <br> <br>  def get_value(self, key, args, kwargs): <br> <br>    if isinstance(key, (int, long)): <br> <br>      return args[key] <br> <br>    else: <br> <br>      return kwargs[key] <br> <br> <br> <br> <br> <br>  def check_unused_args(self, used_args, args, kwargs): <br> <br>    pass <br> <br> <br> <br> <br> <br>  def format_field(self, value, format_spec): <br> <br>    return format(value, format_spec) <br> <br> <br> <br> <br> <br>  def convert_field(self, value, conversion): <br> <br>    # do any conversion on the resulting object <br> <br>    if conversion == 'r': <br> <br>      return repr(value) <br> <br>    elif conversion == 's': <br> <br>      return str(value) <br> <br>    elif conversion is None: <br> <br>      return value <br> <br>    raise ValueError("Unknown converion specifier {0!s}".format(conversion)) <br> <br> <br> <br> <br> <br>  # returns an iterable that contains tuples of the form: <br> <br>  # (literal_text, field_name, format_spec, conversion) <br> <br>  # literal_text can be zero length <br> <br>  # field_name can be None, in which case there's no <br> <br>  # object to format and output <br> <br>  # if field_name is not None, it is looked up, formatted <br> <br>  # with format_spec and conversion and then used <br> <br>  def parse(self, format_string): <br> <br>    return format_string._formatter_parser() <br> <br> <br> <br> <br> <br>  # given a field_name, find the object it references. <br> <br>  # field_name: the field being looked up, e.g. "0.name" <br> <br>  # or "lookup[3]" <br> <br>  # used_args: a set of which args have been used <br> <br>  # args, kwargs: as passed in to vformat <br> <br>  def get_field(self, field_name, args, kwargs): <br> <br>    first, rest = field_name._formatter_field_name_split() <br> <br> <br> <br>    obj = self.get_value(first, args, kwargs) <br> <br> <br> <br>    # loop through the rest of the field_name, doing <br> <br>    # getattr or getitem as needed <br> <br>    for is_attr, i in rest: <br> <br>      if is_attr: <br> <br>        obj = getattr(obj, i) <br> <br>      else: <br> <br>        obj = obj[i] <br> <br> <br> <br>    return obj, first
以上这篇python中string模块各属性以及函数的用法介绍就是小编分享给大家的全部内容了


数据分析咨询请扫描二维码

最新资讯
更多
客服在线
立即咨询