Python string manipulation two built-in functions

Source: Internet
Author: User
Tags printable characters

I. To view the built-in function of a string

>>> dir (str) [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format __ ', ' __ge__ ', ' __getattribute__ ',
' __getitem__ ', ' __getnewargs__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __init_subclass__ ', ' __iter__ ', ' __le__ ', ' __len__ ' ', ' __lt__ ',
' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __rmod__ ', ' __rmul__ ', ' __ Setattr__ ', ' __sizeof__ ',
' __str__ ', ' __subclasshook__ ', ' capitalize ', ' casefold ', ' center ', ' count ', ' encode ', ' endswith ', ' expandtabs ', ' find ', ' Format ',
' Format_map ', ' index ', ' isalnum ', ' isalpha ', ' isdecimal ', ' isdigit ', ' isidentifier ', ' islower ', ' isnumeric ', ' Isprintable ', ' isspace ',
' Istitle ', ' isupper ', ' join ', ' ljust ', ' lower ', ' lstrip ', ' Maketrans ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ' , ' Rpartition ',
' Rsplit ', ' Rstrip ', ' Split ', ' splitlines ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']
In [1]: a = ' 123 ' in [2]: a.a.capitalize    a.endswith      a.index         a.isidentifier  a.istitle       A.lstrip        a.rindex        a.split         a.titlea.casefold      a.expandtabs    a.isalnum       a.islower       a.isupper       A.maketrans     a.rjust         a.splitlines    a.translatea.center        a.find          a.isalpha       A.isnumeric     a.join          a.partition     a.rpartition    a.startswith    a.uppera.count         A.format        a.isdecimal     a.isprintable   a.ljust         a.replace       a.rsplit        a.strip         A.zfilla.encode        a.format_map    a.isdigit       a.isspace       a.lower         a.rfind         A.rstrip        

Second, the commonly used string built-in function

1, capitalize, the first character of a string is capitalized

>>> A = ' Today is a good day. ' >>> a.capitalize () ' Today is a good day. '

2, casefold, all characters lowercase, Unicode all characters are applicable

>>> B ' TODAY is A good day. ' >>> b.casefold () ' Today is a good day. '

3, lower, will all characters lowercase, only for ASCII

>>> B ' TODAY is A good day. ' >>> b.lower () ' Today is a good day. '

4, Upper, capitalize all characters

>>> a ' Today is a good day. ' >>> a.upper () ' TODAY is a good day. '

5, center, returns an original string centered, and uses a space to fill the new string to length width, syntax:str. Center(width[, Fillchar])

>>> a ' Today is a good day. ' >>> A.center (+) '          today is a good day.          '

6, count, used to count the number of occurrences of a character in a string. The optional parameter is the start and end position of the string search, Syntax:str. Count(Sub, start= 0,end=len(string))

>>> a ' Today is a good day. ' >>> a.count (' a ') 3>>> a.count (' A ', 5,-2) 2

7, encode, encodes the string in the encoded format specified by encoding . The errors parameter can specify a different error-handling scheme, Syntax:str. Encode(encoding=' UTF-8 ',errors=' Strict ')

Errors--Sets the processing scheme for different errors. The default is ' strict ', which means a unicodeerror is caused by a coding error. Other possible values are ' ignore ', ' replace ', ' xmlcharrefreplace ', ' backslashreplace ' and any value registered through Codecs.register_error ().

>>> c = ' Hello ' >>> c.encode (encoding= ' utf-8 ') B ' \xe4\xbd\xa0\xe5\xa5\xbd '

8, decode, decodes the string in encoding specified encoding format. The default encoding is string encoding, syntax:str. Decode(encoding=' UTF-8 ',errors=' Strict ')

>>> db ' \xe4\xbd\xa0\xe5\xa5\xbd ' >>> d.decode (encoding= ' utf-8 ') ' Hello '

9, Startwith, checks whether the string starts with the specified substring, returns True if it is, or False. If the parameter beg and end specify a value, the check is within the specified range, syntax:str. StartsWith(str, beg=0,end=len(string))

>>> a ' Today is a good day. ' >>> a.startswith (' Today ') true>>> a.startswith (' Day ') false>>> a.startswith (' Day ', 5) False>>> a.startswith (' Today ', 5) False

10, Endwith, determines whether the string ends with the specified suffix, or returns false if the end of the specified suffix returns true. The optional parameter "start" and "end" are the starting and ending positions of the retrieved string, syntax:str. EndsWith(suffix[, start[, end]])

>>> a ' Today is a good day. ' >>> A.endswith (' Day. ') True>>> A.endswith (' Today. ') False>>> A.endswith (' Day. ', 5) True

11, Expandtabs, the string in the tab symbol (' \ t ') into a space, the tab symbol (' \ t ') The default number of spaces is 8, syntax:str. Expandtabs(tabsize=8)

>>> e = ' Today is a good day. ' >>> e ' \ttoday is \ta good day.\t\t ' >>> e.expandtabs (4) '    today's    a good day.     '

12, find, detects whether the string contains substring str, if specified beg (start) and end (end) range, then checks whether to include within the specified range, if the containing substring returns the starting index value, otherwise returns-1, Syntax:str. Find(str, beg=0, End=len(string))

>>> a ' Today is a good day. ' >>> a.find (' a ') 3>>> a.find (' A ', ten) 17>>> a.find (' abc ')-1

13, index, detects whether the string contains substring str, if you specify the Beg (start) and end (end) range, the check is included in the specified range, the method is the same as the Python find () method, except that if STR does not exist in the string will report an exception, Syntax:str. Index(str, beg=0, End=len(string))

>>> a ' Today is a good day. ' >>> A.index (' a ') 3>>> a.index (' A ', ten) 17>>> A.index (' abc ', ten) Traceback (most recent call Last):  File ' <console> ', line 1, in <module>valueerror:substring not found

14, Isalnum, detect whether the string is composed of letters and numbers

>>> a = ' wang512 ' >>> a.isalnum () true>>> a = ' Wang ' >>> a.isalnum () true>>> A = ' >>> a.isalnum () true>>> a = ' Wang + ' >>> a.isalnum () False

15, Isalnum, detect whether the string is only composed of letters

>>> a = ' Wang ' >>> a.isalpha () true>>> a = ' Up ' >>> a.isalpha () False

16, Isdecimal, check whether the string contains only decimal characters. This method exists only in Unicode objects

>>> a = ' 12345 ' >>> a.isdecimal () true>>> a = ' Wang ' >>> a.isdecimal () False

17, IsDigit, detect whether the string is only composed of numbers

>>> a = ' 12345 ' >>> a.isdigit () true>>> a = ' Wang ' >>> a.isdigit () False

18, Isidentifier, detect whether the string starts with a letter

>>> A.isidentifier () false>>> a = ' Wang ' >>> a.isidentifier () True

19, Islower, detect whether the string is composed of lowercase letters.

>>> a = "Wang" >>> a.islower () true>>> a = "Wang" >>> a.islower () False

20, Isupper, check whether all the letters in the string are uppercase.

>>> a = "Wang" >>> a.isupper () true>>> a = "Wang" >>> a.isupper () False

21, IsNumeric, detect whether the string is only composed of numbers. This method is only for Unicode objects.

>>> a = ' 12345 ' >>> a.isnumeric () true>>> a = ' w123 ' >>> a.isnumeric () False

22, Isprintable, A string containing all printable characters.

23, Isspace, detect whether the string is only composed of spaces.

24, Istitile, check all the words in the string spelling first letter is uppercase, and other letters are lowercase.

25, join, generates a new string, syntax for the elements in the sequence with the specified character connection: str. Join(sequence)

>>> a = [' A ', ' B ', ' C ', ' d ']>>> ', '. Join (a) ' A,b,c,d '

26, Ljust, returns the left alignment of an original string and fills a new string with a space to a specified length. Returns the original string if the specified length is less than the length of the original string, syntax:str. Ljust(width[, Fillchar])

>>> a = ' Wang ' >>> a.ljust (' > ') ' wang>>>>>> '

27, Rjust, returns the right alignment of the original string and fills the new string with a space of length width. Returns the original string if the specified length is less than the length of the string, syntax:str. Rjust(width[, Fillchar])

>>> a = ' Wang ' >>> a.rjust (' < ') ' <<<<<<wang '

28, split, slices the string by specifying a delimiter, and if the parameter num has a specified value, separates only the NUM substring, syntax:str. Split(str="", num=string. Count(str)).

>>> a = ' Wang Wang Wang Wang ' >>> a.split (' A ', 3) [' W ', ' ng w ', ' ng w ', ' ng Wang ']

29, Rsplit

>>> A ' Wang Wang Wang ' >>> a.rsplit (' A ', 3) [' Wang W ', ' ng w ', ' ng w ', ' ng ']

30, Splitlines, separated by line (' \ r ', ' \ r \ n ', \ nthe '), returns a list containing the rows as elements, if the argument keepends is False, does not contain a newline character, and if true, the newline character, syntax:str. Splitlines([keepends])

>>> a = ' ab C\n\nde fg\rkl\r\n ' >>> a.splitlines () [' Ab C ', ', ' de fg ', ' KL ']>>> a.splitlines (Fa LSE) [' AB C ', ', ' de fg ', ' KL ']>>> a.splitlines (True) [' Ab c\n ', ' \ n ', ' de fg\r ', ' kl\r\n ']

31, strip, used to remove the character specified by the string Kinsoku (the default is a space), syntax:str. Strip([chars])

32. Rstrip, delete the specified character at the end of the string (the default is a space), syntax: str. Rstrip([chars])

33, Lstrip, used to truncate the left space of the string or specify the character, syntax: str. Lstrip([chars])

34, Maketrans, used to create the conversion table for character mapping, for the simplest way to call the two parameters, the first argument is a string that represents the character that needs to be converted, the second argument is the target of the string representation of the transformation, syntax:str. Maketrans(intab, outtab)

Note: the length of the two strings must be the same for the one by one corresponding relationship.

35, translate, according to the table given by the parameter tables (256 characters) to convert the character string, the character to be filtered out into the del parameter, syntax:str. Translate(table[, deletechars]);

>>> intab = "Aeiou" >>> outtab = "12345" >>> trantab = ". Maketrans (Intab, outtab) >>> s = ' abcdef ' >>> s.translate (trantab) ' 1bcd2f ' >>> trantab{97:49, 101:50, 105:51, 111:52, 117:53}

36, partition, used to split the string according to the specified delimiter. If the string contains the specified delimiter, a tuple of $3 is returned, the first one is the substring to the left of the delimiter, the second is the delimiter itself, and the third is the substring to the right of the delimiter. Syntax:str. Partition(str)

37, Rpartition

>>> a = "http://www.baidu.com://sina" >>> a.partition ('://') (' http ', '://', ' www.baidu.com://sina ') >>> a.rpartition ('://') (' http://www.baidu.com ', '://', ' Sina ')

38.

Python string manipulation two built-in functions

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.