On Sat, 04 Mar 2006 08:54:33 -0800, s99999999s2003 wrote: > hi > > i have a file with > > xxx.xxx.xxx.xxx:yyy > xxx.xxx.xxx.xxx:yyy > xxx.xxx.xxx.xxx:yyy > xxx.xxx.xxx.xxx > xxx.xxx.xxx.xxx > xxx.xxx.xxx.xxx:yyy > > i wanna split on ":" and get all the "yyy" and print the whole line out > so i did > > print line.split(":")[-1] > > but line 4 and 5 are not printed as there is no ":" to split. It should > print a "blank" at least. > how to print out lines 4 and 5 ? > eg output is > > yyy > yyy > yyy > > > yyy
There are a few ways of handling this problem. It depends on what you want to do if your input string looks like this "abc:y:z": should your code print "y", "z" or even "y:z"? # look before you leap line = "abc:y:z" if ":" in line: print line.split(":")[-1] # prints "z" print line.split(":")[1] # prints "y" print line.split(":", 1)[-1] # prints "y:z" # if your line only has one colon, the above three lines # should all print the same thing else: print "" # look before you leap again L = line.split(":") if len(L) > 1: print L[1] else: print "" # use a sentinel value print (line + ":").split(":", 1)[1][:-1] -- Steven. -- http://mail.python.org/mailman/listinfo/python-list