Python in , In addition to using some built-in functions to obtain information about strings ( for example len() Function to get the length of the string ), The string type itself has some methods for us to use .
Be careful , The method here , Refers to the string type str What it provides , Because of the knowledge of classes and objects , Beginners don't have to delve into , Just know the specific usage of the method .
From this section on , We will introduce some common string type methods , This section first introduces the method of splitting strings split() Method .
split() Method can be used to cut a string into multiple substrings according to the specified separator , These substrings are saved to the list ( Does not contain separators ), Feedback back as the return value of the method . The basic syntax format of this method is as follows :
str.split(sep,maxsplit)
The meanings of the parameters in this method are respectively :
stay split In the method , If you don't specify sep Parameters , Need to be str.split(maxsplit=xxx) The format of maxsplit Parameters .
Same as built-in function ( Such as len) It's used in different ways , Methods owned by string variables , Only use “ character string . Method name ()” Method call . There's no need to worry about why , After learning classes and objects , It's natural to understand .
for example , Define a save C Language: the string of Chinese web address , And then use split() Method is separated according to different delimiters , The execution process is as follows :
>>> str = "C Chinese language network >>> c.biancheng.net"
>>> str
'C Chinese language network >>> c.biancheng.net'
>>> list1 = str.split() # Split with default separator
>>> list1
['C Chinese language network ', '>>>', 'c.biancheng.net']
>>> list2 = str.split('>>>') # Use multiple characters for segmentation
>>> list2
['C Chinese language network ', ' c.biancheng.net']
>>> list3 = str.split('.') # use . No split
>>> list3
['C Chinese language network >>> c', 'biancheng', 'net']
>>> list4 = str.split(' ',4) # Use spaces to divide , And stipulates that it can only be divided into 4 Substring
>>> list4
['C Chinese language network ', '>>>', 'c.biancheng.net']
>>> list5 = str.split('>') # use > Character segmentation
>>> list5
['C Chinese language network ', '', '', ' c.biancheng.net']
>>>
It should be noted that , In unspecified sep When parameters are ,split() Method uses null characters for segmentation by default , But when there are consecutive spaces or other empty characters in the string , Will be treated as a separator to split the string , for example :
>>> str = "C Chinese language network >>> c.biancheng.net" # contain 3 Consecutive spaces
>>> list6 = str.split()
>>> list6
['C Chinese language network ', '>>>', 'c.biancheng.net']
>>>