[Tutor] Splitting strings and undefined variables
iwasroot at gmail.com
Mon Feb 9 21:05:33 CET 2009
I was looking at this:
I have a question about the line of code that uses split()
With the python version, the line below only works if there are three
fields in line.
(first, last, passwd) = line.split()
Also, since the variables are used like this:
lineout = "%s:%s:%d:%d:%s %s,,/home/%s:/bin/bash\n" % \
(user, passwd, uid, gid, first, last, user)
I can't use ":".join(line.split())
But maybe a dictionary could be used for string substitution.
In the perl version (above the python version in the link), the script
works with the input line having one to three fields. Like "fname
lname pw" or "fname lname"
($n1, $n2, $n3) = split / /;
Is there a better way to extract the fields from line in a more
flexible way, so that the number of fields could vary?
I guess we could use conditionals to check each field, but is there a
more elegant (or pythonic!) way to do it?
P.S. I'm not a Perl user, I was just reading the examples. I've been
using C and awk for few years, and Python for few months. Also, I know
blank passwords aren't very practical, but I'm just asking this to
explore possibilities :)
More information about the Tutor