converting from perl: variable sized unpack
John Machin
machin_john_888 at hotmail.com
Sat Jul 14 04:29:07 EDT 2001
Roy Smith <roy at panix.com> wrote in message news:<roy-B2459F.22112513072001 at news1.panix.com>...
> What's the best way to translate this perl snippet into python:
>
> ($f1, $f2, $f3, $f4, $f5, $f6) = split ('\s+', $line);
>
> The obvious translation would be:
>
> [f1, f2, f3, f4, f5, f6] = string.split (line)
>
> but the problem is that line may have fewer than 6 fields on it. Perl
> handles this smoothly by leaving the "extra" variables undefined, whereas
> python raises a ValueError exception. What I'd like to do is have the
> extra field variables left as null strings.
Try this:
f1, f2, f3, f4, f5, f6, extra_guff = (line.split(None, 6) + 7 * [""])[:7]
if extra_guff:
print "Oops! More data than expected!"
# or, more likely, an unintended space in a data field
Smooth enough?
More information about the Python-list
mailing list