Python split method splits string by separators

Split a string

The split method does the reverse of join method. It splits a string to sequence. The split method has the following syntax.

s.split([sep [, maxsplit]])

It returns a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator.


#   www . j  a va2s  .  co  m
sentence = "A Simple Sentence."
print sentence.split()


string1 = "A, B, C, D, E, F"
print "String is:", string1
print "Split string by spaces:", string1.split()
print "Split string by commas:", string1.split( "," )
print "Split string by commas, max 2:", string1.split( ",", 2 )
print

s = "this   is\na\ttest"                  
print s 
print s.split()                                
print " ".join(s.split())                     


entry =  "Name:James:Occupation:Software Engineer"
print entry.split(':')

The code above generates the following result.

'a*b'.split('*') yields ['a','b'].

Use list(s) to convert a string to a list of characters (e.g., ['a','*','b']).


print '1+2+3+4+5'.split('+') 
print '/usr/bin/env'.split('/') 
print 'Using   the   default'.split() 

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary