Python character string operations-python cookbook

Source: Internet
Author: User

I. Text
1. process one character each time
Thelist = list (thestring) # convert a string to a Character Sequence
2. Conversion between characters and character values
>>> Print ord ('A ')
97
>>> Print chr (97)
A
>>> Print ord (u' I ')
25105
>>> Print unichr (25105) # maximum to 65535
Me
3. Determine whether a variable is of the string type.
(1) def isString (anobj ):
Return type (anobj) is type ('') # insufficient: The self-compiled str subclass cannot pass the test, unicode
No.
(2) def isAString (anobj ):
Return isinstance (anobj, basestring) # The built-in type basestring is the base of Both str and unicode.
Class.
4. String alignment
Print 'hej'. center (20, '+'), 'hej'. ljust (20), 'hej'. Must ust (20)
5. Remove spaces at both ends of the string
X = 'hej'
X. lstrip (), x. rstrip (), x. strip ()
6. Merge strings
Pieces = ['A', 'bdd', 'aas ']
LargeString = ''. join (pieces)
LargeString = '% s % something' % (small1, small2)
7. Character-by-character string or word-by-word flip
Revchars = astring [:-1] # flip by character
Revchars = ''. join (astring. split () [:-1]) # Flip word by word
Revchars = ''. join (reversed (astring. split () # Flip word by word
8. Check whether the string contains characters in a character set.
Def contens (seq, aset ):
""""""
A = []
For c in seq:
If c in aset:
A. append (c)
Contens (list ('AB'), 'adfd ')
9. Use the string's translate method
Def translator (frm = '', to ='', delete = '', keep = None ):
If len (to) = 1:
To = to * len (frm)
Trans = string. maketrans (frm,)
If keep is not None:
Allchars = string. maketrans ('','')
Delete = allchars. translate (allchars, keep. translate (allchars, delete ))
Def translate (s ):
Return s. translate (trans, delete)
Return translate
Digits_only = translator (frm = '000000', to = 'abc', keep = string. digits)
Print digits_only ('adsfa123 ')
Note: string. maketrans ('A', 'B') returns a string that replaces a with B.
The length is 256 characters long. Therefore, the length of the two parameters must be consistent.
String. maketrans ('','') returns the string of all character sets.
String. translate (s, trans, delete) is to get a copy of s, replace the character according to the ing relationship in trans,
Delete the corresponding characters based on the characters in the delete statement.
10. filter the characters that do not belong to the specified set in the string www..2cto.com
ASCII code version:
Import string
Allchars = string. maketrans ('','')
#----------------------------------------------------------------------
Def makefilter (keep ):
""""""
Delchars = allchars. translate (allchars, keep)
Def thefilter (s ):
""""""
Return s. translate (allchars, delchars)
Return thefilter
If _ name __= = '_ main __':
Just_vowels = makefilter ('20140901 ')
Print just_vowels ('adfsadf1221ddfdsa ')
UNICOED version:
#-*-Coding: UTF-8 -*-
Import string
Import sets
######################################## ################################
Class Keeper (object ):
""""""
Def _ init _ (self, keep ):
"" Constructor """
Self. keep = sets. Set (map (ord, keep ))
Def _ getitem _ (self, n ):
""""""
If n not in self. keep:
Return None
Return unichr (n)
Def _ call _ (self, s ):
""""""
Return s. translate (self)
Makefilter = Keeper
If _ name __= = '_ main __':
Just_vowels = makefilter (u' I ')
Print just_vowels (u'who am I ')

11. Change the case sensitivity.
>>> 'Asdf '. upper () # All characters are capitalized.
'Asdf'
>>> 'Asdf '. lower () # lowercase letters of all characters
'Asdf'
>>> Print 'My name IS '. capitalize () # The first character of the string IS capitalized.
My name is
>>> Print 'My naMe iS '. title () # The first character of each word in a string iS capitalized.
My Name Is
12. Access the substring
Afield = theline [] # Only one field can be retrieved at a time
16. Replace the substring in the string
#-*-Coding: UTF-8 -*-
Import string
Def expand (format, d, marker = '"', safe = True ):
""""""
If safe:
Def lookup (w): return d. get (w, w. join (['',''])
Else:
Def lookup (w ):
Return d [w]
Parts = format. split (marker)
Parts [: 1] = map (lookup, parts [: 1])
Return ''. join (parts)
If _ name __= = '_ main __':
Print expand ('just "a" test', {'A': 'one '})
Note: 'as'. join (['A', 'B']) will connect 'A', 'B'. The connection uses 'as' and the result is 'aasb'
The get method of the list array and the join method of the string are not clear yet.
17. Replace the substring in the string
#-*-Coding: UTF-8 -*-
Import string
New_style = string. Template ('this is $ this ')
Print new_style.substitute ({'this': 5 })
Print new_style.substitute (this = 'sadf ')
18. Check the end mark in the string
#-*-Coding: UTF-8 -*-
Import OS
Import itertools
#----------------------------------------------------------------------
Def anyTrue (predicate, sequence ):
""""""
Return True in itertools. imap (predicate, sequence)
#----------------------------------------------------------------------
Def endsWith (s, * endings ):
""""""
Return anyTrue (s. endswith, endings)


For filename in OS. listdir ('.'):
If endsWith(filename,'.jpg ','. py '):
Print filename

19. use unicode to process international text
Unicodestring = u'hello world'
Utf8string = unicodestring. encode ("UTF-8 ")
Isostring = unicodestring. encode ("ISO-8859-1 ")

 


From Chen jianhong (java, python)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.