• What is Python String split() function?

    What is Python String split() function?

    Silver Member Asked on June 5, 2018 in Python.
    Add Comment
  • 2 Answer(s)

    The split() method breaks up a string at the specified separator and returns a list of strings.
    The syntax of split() is:

    
    str.split([separator [, maxsplit]])
    
    

    split() Parameters
    The split() method takes maximum of 2 parameters:

    separator (optional)- The is a delimiter. The string splits at the specified separator.
    If the separator is not specified, any whitespace (space, newline etc.) string is a separator.
    maxsplit (optional) – The maxsplit defines the maximum number of splits.
    The default value of maxsplit is -1, meaning, no limit on the number of splits.

     

    text= 'Love thy neighbor'
    # splits at space
    
    print(text.split())
    grocery = 'Milk, Chicken, Bread'
    # splits at ','
    
    print(grocery.split(', '))
    # Splitting at ':'
    
    print(grocery.split(':'))
    

     

    Output:-

    ['Love', 'thy', 'neighbor']
    
    ['Milk', 'Chicken', 'Bread']
    
    ['Milk, Chicken, Bread']
    
    
    Silver Member Answered on June 5, 2018.
    Add Comment
     word = 'geeks, for, geeks, pawan'
     # maxsplit: 0
    print(word.split(', ', 0))
     # maxsplit: 4
    print(word.split(', ', 4))
     # maxsplit: 1
     Output
    ['geeks, for, geeks, pawan']
     ['geeks', 'for', 'geeks', 'pawan']
     ['geeks', 'for, geeks, pawan']
    
    Silver Member Answered on June 5, 2018.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.