python string split example 2.7.2
6 lines of code, no modules to import
x = 'joe fred terry mitch jane betty mary ellen' while (1==1): y = x.find(" ") if y==-1: break print 'next name ',x[:y] x = x[y+1:]
3 lines of code, using the string module. Elegant because the loop definition is overt and evident.
import string x = 'joe fred terry mitch jane betty mary ellen' for name in string.split(x): print 'next name ',name
Other Examples
- split a semicolon delimitted string, or any delimiter in a string of fields
- some string library in python constants
- search a string (you don’t need the string library), i.e. ‘pos’ or re.search
import string x = 'joe;fred;terry;mitch;jane;betty;mary;ellen' for name in string.split(x,';'): print 'next name ',name
import string print "1..",string.printable print "2..",string.uppercase print "3..",string.letters print "4..",string.digits print "5..",string.punctuation
x='joe,john' print x.index('john') # this yields the integer '4' print x[4:] # this would print john, or the rest of the string which is here john