Python STR Parsing

Source: Internet
Author: User

Python built-in string class (requires no import); it provides many common string processing functions.
The STR member function does not affect the call of the string itself, and returns a processed copy.

S. Center (width [, fillchar])-> string
Fill "S" to "width" with fillchar (which must be a character, with a space by default), and center "S.
Similar to ljust, just UST

>>> S = "notice"
>>> S. Must ust (20 ,'*')
* Notice'
>>> S. Ljust (20 ,'*')
'Notice **************'
>>> S. Center (20 ,'*')
* Notice *******'

>>> S. Center (20 ,"-*")
Traceback (most recent call last ):
File "<pyshell #32>", line 1, in <module>
S. Center (20 ,"-*")
Typeerror: Center () Argument 2 must be char, not Str
>>> S. Center (1)
'Notice'

S. lstrip ([chars])-> string or Unicode
Remove the character specified by chars in the starting part of S. Chars can be multiple characters (different from the center). The default character is blank.
As long as the characters starting with S are excluded from the Chars parameter, rather than matching the Chars parameter as a whole.
If chars is Unicode, first convert s to Unicode and then strip.
Similar to strip and rstrip

>>> S = string. whitespace
>>> S. lstrip ()
''
>>> S = "ababcxyz"
>>> S. lstrip ("ABC ")
'Xyz'
>>> S
'Ababcxyz'

S. endswith (suffix [, start [, end])-> bool
Test whether s [start: end] ends with suffix.
Suffix can also be a tuple consisting of strings. If an element in the tuple passes the test, true is returned.
Similar to startswith

>>> S = "this is a test ."
>>> S. endswith ("test .")
True
>>> Test = ("test", "a test ")
>>> S. endswith (test)
False
>>> Test = ("test", "test .")
>>> S. endswith (test)
True

>>> S = "startswith"
>>> S. startswith ("star ")
True
>>> S. startswith ("stat ")
False
>>> Slist = ("State", "Spar ")
>>> S. startswith (slist)
False
>>> Slist = ("Spar", "art ")
>>> S. startswith (slist, 2)
True

S. Count (sub [, start [, end])-> int
Returns the number of times that sub does not appear repeatedly in S [start: end.

>>> S = "banana"
>>> S. Count ("")
2
>>> S. Count ("Ana ")
1
>>> S. Count ("Nan",-3)
0

S. Find (sub [, start [, end])-> int
Returns the position where sub appears for the first time in s [start: end]; returns-1 (different from index) if the search fails ).
Similar to rfind.

>>> S = "Mississippi"
>>> S. rfind ("ssi ")
5
>>> S. Find ("ssi ")
2
>>> S. Find ("mm ")
-1
>>> S. rfind ("mm ")
-1

S. Index (sub [, start [, end])-> int
Similar to S. Find (), except: valueerror is thrown when the query fails.
Similar to rindex

>>> S = "this is a test ."
>>> S. Index ("is ")
2
>>> S. Index ("is", 3)
5
>>> S. Index ("is", 6)

Traceback (most recent call last ):
File "<pyshell #52>", line 1, in <module>
S. Index ("is", 6)
Valueerror: substring not found

S. isalnum ()-> bool
Test whether the character in a non-null string is either a letter or a number, that is, ~ Za ~ Z0 ~ 9.
Similar to isalpha, isdigit, and isspace, different from islower and isupper, these functions test each character in S and return false if they do not match.

>>> Import string
>>> All = string. Letters + String. digits
>>> All
'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789'
>>> All. isalnum ()
True
>>> None = string. punctuation
>>> None
'! "# $ % &/'() * +,-./:; <=>? @ [//] ^ _ '{| }~ '
>>> None. isalnum ()
False
>>> A = ""
>>> A. isalnum ()
False
>>> A = "this is a test"
>>> A. isalnum ()
False

S. isalpha ()-> bool
Test whether all non-null strings are letters.

>>> A = "ab12"
>>> A. isalpha ()
False
>>> A = "AB"
>>> A. isalpha ()
True

S. isdigit ()-> bool
Test whether all non-null strings are numbers.

>>> "Ab12". isdigit ()
False
>>> "12". isdigit ()
True
>>> "3.14". isdigit ()
False

S. isspace ()-> bool
Test whether all non-null strings are empty.

>>> Import string
>>> String. whitespace
'/T/N/x0b/x0c/R'
>>> String. whitespace. isspace ()
True
>>> "/T/N". isspace ()
True
>>> "_". Isspace ()
False

S. islower ()-> bool
Test whether all uppercase and lowercase letters in a non-null string are lowercase letters.
Similar functions include isupper, lower, upper, and swapcase. These functions only test uppercase and lowercase letters, while ignoring other characters.

>>> "Pi = 3.14". islower ()
True
>>> "". Islower ()
False
>>> "Pi = 3.14". islower ()
False
>>> "Pi = 3.14". isupper ()
True
>>> S = "Beijing 2008"
>>> S. Lower ()
'Beijing 2008'
>>> S. Upper ()
'Beijing 2008'
>>> S
'Beijing 2008'

S. Join (sequence)-> string
Link each string in the sequence with the S Separator
When Len (sequence) <= 1, S is not returned.

>>> S = ["this", "is", "Beijing"]
>>> "_ * _". Join (s)
'This _ * _ is _ * _ Beijing'
>>> "". Join (s)
'Thisbeijing'

>>> "*". Join ("1234 ")
'1*2*3*4'

>>> S = ["Beijing"]
>>> A. Join (s)
'Beijing'
>>> S = []
>>> A. Join (s)
''

S. Split ([Sep [, maxsplit])-> List of strings
Returns a list composed of strings: separated by the separator "Sep" (which can be a string). If the separator "Sep" is not specified or "NONE", the separator is blank.
SEP does not appear in the returned value list. There must be an element around SEP in the returned result.

>>> S = "Mississippi"
>>> S. Split ('s ')
['Mi', '', 'I','', 'ippi ']
>>> S. Split ('ss ')
['Mi ',' I ', 'ippi']

>>> S = "1/T2/n/T3/n/t end"
>>> Print s
1 2
3
End
>>> S. Split ()
['1', '2', '3', 'end']

>>> S = ""
>>> S. Split ("SS ")
['']
>>> S = "hello"
>>> S. Split ()
['Hello']

>>> S = "AAAAA"
>>> S. Split ("AA ")
['','', 'A']

>>> S = "Onion"
>>> S. Split ("On ")
['', 'I','']

S. splitlines ([keepends])-> List of strings
Returns a list composed of rows in S. To include a line break in each element of the list, set keepends to true.

>>> S = "first/nsecond/nend"
>>> Print s
First
Second
End
>>> S. splitlines ()
['First', 'second', 'end']
>>> S. splitlines (true)
['First/N', 'second/N', 'end']

>>> S = "/None Line/N"
>>> S. splitlines ()
['', 'One Line']
>>> S. Split ("/N") # note the difference
['', 'One Line','']

S. Partition (SEP)-> (Head, SEP, tail)
Take the first appearance of SEP in s as the separator, split S into three parts, and return.
There is also rpartition.

>>> S = 'Mississippi'
>>> S. Partition ('ssi ')
('Mi', 'ssi ', 'ssippi ')
>>> S. rpartition ('ssi ')
('Missi', 'ssi ', 'ppi ')

>>> S. Partition ("NONE ")
('Mississippi ','','')
>>> S. rpartition ("NONE ")
('','', 'Mississippi ')

S. Replace (old, new [, Count])-> string
Returns a copy: replace all the old values in S with new. If count is specified, replace the previous count.

>>> S = "_-_-_"
>>> S. Replace ("_","**")
'**-**-**'
>>> S. Replace ("_", "**", 1)
'**-_-_'
>>> S
'_-_-_'

Related Article

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.