Explanation of Python split of Function Example Usage

  • 2021-08-28 20:38:36
  • OfStack

In Python, the split () method cuts a string into several substrings according to the specified separator, which are saved in the list (without the separator) and fed back as the return value of the method.

Usage of split function


split(sep=None, maxsplit=-1)

Parameter

The sep separator defaults to all null characters, including spaces, newlines (\ n), tabs (\ t), and so on.

maxsplit division times. The default is-1, which separates all.

Example:


//  Example 
String = 'Hello world! Nice to meet you'
String.split()
['Hello', 'world!', 'Nice', 'to', 'meet', 'you']
String.split(' ', 3)
['Hello', 'world!', 'Nice', 'to meet you']
String1, String2 = String.split(' ', 1) 
//  You can also split the string and return it to the corresponding n Target, but pay attention to whether there is a delimiter at the beginning of the string. If there is a delimiter, it will be divided 1 Empty string 
String1 = 'Hello'
String2 = 'world! Nice to meet you'
String.split('!')
//  Select another separator 
['Hello world', ' Nice to meet you']

Implementation of split function


 def split(self, *args, **kwargs): # real signature unknown
    """
    Return a list of the words in the string, using sep as the delimiter string.
     sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
     maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.
    """
    pass

The picture above shows the Pycharm document


def my_split(string, sep, maxsplit):
  ret = []
  len_sep = len(sep)
  if maxsplit == -1:
    maxsplit = len(string) + 2
  for _ in range(maxsplit):
    index = string.find(sep)
    if index == -1:
      ret.append(string)
      return ret
    else:
      ret.append(string[:index])
      string = string[index + len_sep:]
  ret.append(string)
  return ret
if __name__ == "__main__":
  print(my_split("abcded", "cd", -1))
  print(my_split('Hello World! Nice to meet you', ' ', 3))

Related articles: