This article and everyone to share is mainly Python in the string module related content, come together to see it, I hope that you learn Python Helpful. The string module contains a number of practical constants and classes, as well as some obsolete legacy functionality, and can also be used as String operations.1. Common MethodsStr.capitalize () capitalizes The first letter of the string Str.center (width) fills the original string with a space into a string of length width , The original string content centered Str.count (s) return string s number of occurrences in str str.decode (encoding= ' UTF-8 ', errors= ' strict ') Decodes the string Str.encode (encoding= ' UTF-8 ', errors= ' strict ') in the specified encoding format encodes the string in the specified encoding format str.endswith (s) Judging the string str whether to string s end Str.find (s) return string s position index in string str , no return - 1str.index (s) and find () method, But if s does not exist in str it throws an exception str.isalnum () IF str returns at least one character and is either a letter or a number return True, otherwise returns falsestr.isalpha () if str At least one character and all letters return True, return falsestr.isdigit () returns if str contains only numbers true returns falsestr.islower () If the str has case-sensitive characters and is lowercase then returns True returns falsestr.isspace () returns   TRUE&NBSP if str contains only spaces, otherwise returns Falsestr.istitle () If str is a heading (  ) Returns true , otherwise returns falsestr.isupper () If str there are case-sensitive characters, And both are uppercase returns True otherwise returns falsestr.ljust (width) returns an original string left-aligned and padded to length with spaces width The new string Str.lower () Convert str all uppercase characters to lowercase str.lstrip () Remove str left invisible character Str.partition (s) s divides str tangent into three values str.replace (a, b) replaces str in the string a with Bstr.rfind (s) resembles find () function, but looks from the right to Str.rindex (s) similar to index () It's just starting from the Right. str.rjust (width) Returns a new string with the right alignment of the original string and padding to length width with spaces str.rpartition (s) similar to partition () Function , just start from the right to find Str.rstrip () Remove the invisible character str right str.split (s) to s for separator slices strstr.splitlines () separated by rows, returns a list containing each row as an element str.startswith (s) checking the string str Whether to start with s , is to return true , otherwise returns falsestr.strip () equals simultaneous execution of rstrip () and lstrip () str.title () Back caption str, all words start with uppercase, the remaining letters are lowercase str.upper () return str All characters are uppercase string Str.zfill (width) return string with length width , original string str right-aligned, front padding 0 2. String ConstantsString.ascii_lowercase Small Letter ' abcdefghijklmnopqrstuvwxyz ' string.ascii_uppercase uppercase letters ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ' String.ascii_lettersascii_lowercase and Ascii_uppercase constants concatenate strings string.digits numbers 0 through 9: ' 0123456789 ' string.hexdigits string ' 0123456789abcdefABCDEF ' string.letters string ' ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ ' string.lowercase Small Letter string ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ' string.octdigits string ' 01234567 ' string.punctuation all punctuation characters string.printable printable characters of the String. String ' abcdefghijklmnopqrstuvwxyz ' string.whitespace blank character ' \t\n\x0b\x0c\r ' with numbers, letters, punctuation and spaces String.uppercase University letters3. String Templates templateThrough String. The Template can customize the replacement of strings for Python, as Follows: >>>from string Import template>>>s = Template (' $who like $what ' ) >>>print s.substitute (who= ' i ', what= ' python ') i like python>>>print s.safe_substitute (who= ' I ') # missing Key does not throw the wrong I like $what >>>template (' ${who}likepython '). substitute (who= ' I ') # use {} ' Ilikepython ' Template when inside a string There are more advanced usages that can be inherited by String. template, overriding variable delimiter (delimiter) and Idpattern (substitution format), customizing different forms of Templates.ImportStringtemplate_text = "Delimiter: $de replaced:%with_underscore ingored:%notunderscored ' d = {' de ': ' not replace D ', ' With_underscore ': ' replaced ', ' notunderscored ': ' not replaced '}classMyTemplate(string. template): # Rewrite the stencil delimiter (delimiter) to "%", the replacement pattern (idpattern) must contain an underscore (_) delimiter = '% ' Idpattern = ' [a-z]+_[a-z]+ 'PrintString. Template (template_text). Safe_substitute (d) # using the original template renderingPrintMyTemplate (template_text). Safe_substitute (d) # using the rewritten MyTemplate render output: Delimiter:not Replacedreplaced:%with_undersco Reingored:%notunderscoreddelimiter: $deReplaced: replacedingored:%notunderscored Native template only renders the case of the qualifier, after the rewritten myte Mplate renders the delimiter as% and replaces the format with an Underscore.4. Common String Tricks· 1. Invert string >>> s = ' 1234567890 ' >>> print s[::-1]0987654321 2. about string links try to use the Join () link string, because the ' + ' sign connects n strings to request n-1 memory, using join () requires 1 times of memory. 3. Fixed-length Split String >>>Importre>>> s = ' 1234567890 ' >>> re.findall (r '. { 1,3} ', S) # has three lengths of split strings [' 123 ', ' 456 ', ' 789 ', ' 0 '] 4. Use () parentheses to generate a string of sql = ('SELECTCount() fromTable’’WHERE ID= "10" "GROUP bySex ') Print Sqlselect count () from table WHERE id = "ten" GROUP by sex 5. Write the print string to file >>> print >> open ("somefile.txt", "w+"), "hello world" # Hello World will write to the file Somefile.tx to source: Bole Online
A detailed description of the Python learning string module