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

  1. split a semicolon delimitted string, or any delimiter in a string of fields
  2. some string library in python constants
  3. 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

0 thoughts on “python string split example 2.7.2”

  1. Your means of explaining the whole thing in this paragraph is actually fastidious, all can simply
    know it, Thanks a lot.

  2. Write more, thats all I have to say. Literally, it seems
    as though you relied on the video to make your point. You definitely know what youre talking about, why throw away your intelligence on just posting videos to your
    weblog when you could be giving us something enlightening to read?

Leave a Reply

Your email address will not be published. Required fields are marked *