
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模塊各屬性以及函數的用法介紹就是小編分享給大家的全部內容了
數據分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
2025 年,數據如同數字時代的 DNA,編碼著人類社會的未來圖景,驅動著商業時代的運轉。從全球互聯網用戶每天產生的2.5億TB數據, ...
2025-05-27CDA數據分析師證書考試體系(更新于2025年05月22日)
2025-05-26解碼數據基因:從數字敏感度到邏輯思維 每當看到超市貨架上商品的排列變化,你是否會聯想到背后的銷售數據波動?三年前在零售行 ...
2025-05-23在本文中,我們將探討 AI 為何能夠加速數據分析、如何在每個步驟中實現數據分析自動化以及使用哪些工具。 數據分析中的AI是什么 ...
2025-05-20當數據遇見人生:我的第一個分析項目 記得三年前接手第一個數據分析項目時,我面對Excel里密密麻麻的銷售數據手足無措。那些跳動 ...
2025-05-20在數字化運營的時代,企業每天都在產生海量數據:用戶點擊行為、商品銷售記錄、廣告投放反饋…… 這些數據就像散落的拼圖,而相 ...
2025-05-19在當今數字化營銷時代,小紅書作為國內領先的社交電商平臺,其銷售數據蘊含著巨大的商業價值。通過對小紅書銷售數據的深入分析, ...
2025-05-16Excel作為最常用的數據分析工具,有沒有什么工具可以幫助我們快速地使用excel表格,只要輕松幾步甚至輸入幾項指令就能搞定呢? ...
2025-05-15數據,如同無形的燃料,驅動著現代社會的運轉。從全球互聯網用戶每天產生的2.5億TB數據,到制造業的傳感器、金融交易 ...
2025-05-15大數據是什么_數據分析師培訓 其實,現在的大數據指的并不僅僅是海量數據,更準確而言是對大數據分析的方法。傳統的數 ...
2025-05-14CDA持證人簡介: 萬木,CDA L1持證人,某電商中廠BI工程師 ,5年數據經驗1年BI內訓師,高級數據分析師,擁有豐富的行業經驗。 ...
2025-05-13CDA持證人簡介: 王明月 ,CDA 數據分析師二級持證人,2年數據產品工作經驗,管理學博士在讀。 學習入口:https://edu.cda.cn/g ...
2025-05-12CDA持證人簡介: 楊貞璽 ,CDA一級持證人,鄭州大學情報學碩士研究生,某上市公司數據分析師。 學習入口:https://edu.cda.cn/g ...
2025-05-09CDA持證人簡介 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度、美團、阿里等 ...
2025-05-07相信很多做數據分析的小伙伴,都接到過一些高階的數據分析需求,實現的過程需要用到一些數據獲取,數據清洗轉換,建模方法等,這 ...
2025-05-06以下的文章內容來源于劉靜老師的專欄,如果您想閱讀專欄《10大業務分析模型突破業務瓶頸》,點擊下方鏈接 https://edu.cda.cn/g ...
2025-04-30CDA持證人簡介: 邱立峰 CDA 數據分析師二級持證人,數字化轉型專家,數據治理專家,高級數據分析師,擁有豐富的行業經驗。 ...
2025-04-29CDA持證人簡介: 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度,美團,阿里等 ...
2025-04-28CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-27數據分析在當今信息時代發揮著重要作用。單因素方差分析(One-Way ANOVA)是一種關鍵的統計方法,用于比較三個或更多獨立樣本組 ...
2025-04-25