#!/usr/bin/env python#-*- coding:utf-8 -*-##################################################### # author: sunfx [email protected]# last modified: 2014/11 /11# filename: string.py# q q Group: 236147801############## ###################################### #import reimport stringstr = ' i love Python ' #1. Generates a 20-character length Print str.center () #2. Aligns print str.ljust #3. Word Aligns alignment print str.rjust (20) # 4.str right-aligned, padding 0print str.zfill (#5) on the left. All characters uppercase Print str.upper () #6. All characters go to lowercase print str.lower () #7. Capitalize the first letter of all words s = ' thi quick brown fox jumped over the lazy dog. ' Print sprint string.capwords (s) #8. Capitalization print str.swapcase () #9. The delimiter is marked, the first character is capitalized, and the remaining lowercase print Str.title () #10. Template conversion character substitution more efficient than replace Leet = string.maketrans (' Abegiloprstz ', ' 463611092572 ' ) s = ' Thi quick brown fox jumped over the lazy dog. ' Print sprint s.translate (leet) str = ' 0123 ' #11. Are all letters and numbers, and at least one character Print str.isalnum () # 12. Are all numbers and at least one character print str.isdigit () #13. Determines whether all letters are full, and at least one character print str.isalpha () #14. Determine if it is lowercase, When all are lowercase and numbers together, it is also judged as Trueprint str.islower () #15. Determines whether it is a white space character, and has at least one character print str.isspace () #16. Determines whether a character is print str.startswith (' str ') at the beginning of str #17. The interpretation character is terminated with Str print str.endswith (' str ') str = ' String 1eamd ' #18. Look for character, no return-1, is responsible for returning to the first matching index print str.find (' a ') #19. Find character, no return-1, is responsible for returning to the last matched index print str.rfind (' a ') #20. To find the character, if there is no error, it is the responsibility to return to the first matching index print str.index (' s ') #21. Find the character, no error, and be responsible for returning to the last matching index print str.rindex (' s ') #22. Find the number of occurrences of a string in a character print str.count (' s ') #23. Replace the matching character print str.replace (' s ', ' A ') #24. Removes the string-to-match character, which is commonly used to remove the carriage return Print str.strip (' n ') #25. Delete the matching character print str.lstrip (' n ') on the left #26. Delete the matching characters on the right print Str.rstrip (' n ') #27. Turn tabs into spaces str = ' tab ' Print str.expandtabs () str = ' I'm learning ' #28. The decoding process, decoding utf-8 to Unicodeprint str.decode (' Utf-8 ') #29. Encoding process, encoding Unicode to Gbkprint str.decode (' Utf-8 '). Encode (' GBK ') #30. Speak Unicode encoding utf-8print Str.decode (' Utf-8 '). Encode (' Utf-8 ') #31. Character segmentation str = ' learn string ' print '-'. Join (str) #32. What is the split print str.split (' ') #33. Template template values = {' var ': ' foo '}t = string. Template ("" " Variale : $var escape : $$ variable in text: ${var}iable "" ") print ' TEMPLATE: ', T.substitute (values) s = " "" variale : % (Var) s escape : %% variable in text: % (Var) siable "" "print ' Interpolation: ', s % values#34.template exception handling t = string. Template ("$var is here but $missing is not provided") try: print ' substitute () : ', T.substitute (values) except keyerror, err:print ' ERROR: ', STR (ERR) print ' Safe_substitute (): ', T.safe_substitute (values) #36. Advanced Template template_text = " delimiter : %% replaced : %with_ Underscore ignored : %notundersocred ' #37. You can customize the templace Conversion rules d = { ' with_underscore ': ' Replaced ', ' notundersocred ': ' Not replaced '}class mytemplate (string. Template):d elimiter = '% ' idpattern = ' [a-z]+_[a-z]+ ' T = mytemplate (template_text ) print ' Modified id pattern: ' Print t.safe_substitute (d) #38. Customize more complex rules t = string. Template (' $var ') Print t.pattern.pattern ' \$ (?: (? p<escaped>\$) | # Escape sequence of two delimiters #忽略的分隔符 (? p<named>[_a-z][_a-z0-9]*) | # delimiter and a python identifier #python分隔符的标识 (i.e. variable) {(? p<braced>[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier #分隔符和一个支撑的标识 (? p<invalid>) # other ill-formed delimiter exprs #无效的 ) ' Class mytemplate ( String. Template):d elimiter = ' {' #定义转义符pattern = r ' \{\{(??: (? P<escaped>\{\{) | (? p<named>[_a-z][_a-z0-9]*) \}\} | (? p<braced>[_a-z][_a-z0-9]*) \}\} | (? p<invalid>) ' t = mytemplate (' {{{{ {{var}} "print t.template #查看template的值print ' MATCHES: ', T.pattern.findall (t.template) #查看正则匹配到的字符print ' substiituted: ', T.safe_substitute (var= ' replacement ') #使用替换print mytemplate.delimiter #查看mytemplate转义符print string. template.delimiter #查看string转义符 #http://legacy.python.org/dev/peps/pep-0292/#格式化段落 #39. Fill paragraph left-aligned, first line indent, Row Hollow cell continues to retain import textwrapsample_text = ' The Textwrap modulde can be used to format text for output in situations where pretty-parinting is desired. It offers programmatic functionality similar to the paragraph wrapping or filling features found in Myany text editors. " print ' no dedent:\n ' Print textwrap.fill (sample_text,width=50) #40. Remove existing indents (remove all spaces in the line) Dedemted_text = textwrap.dedent (Sample_text) print dedemted_text#41. Combine fill and dedent to specify the width of the output text Dedemted_text = textwrap.dedent (Sample_text). Strip () print dedemted_textfor width in [45,70]: print '%d columns:\n ' % widthprint textwrap.fill (dedemted_text,width=width) print#42. Hanging indent Print textwrap.fill (dedemted_text, initial_indent= ', #定义文本第一行缩进的长度 subsequent_indent= ' ' * 4, #定义其他行的缩进 width=50 #定义文本长度, default 75)
This article is from the "brotherxing" blog, make sure to keep this source http://brotherxing.blog.51cto.com/3994225/1575552
Python string usage learn ing