#!/usr/bin/python3 """I constructed the following off the cuff as an example of the kind of case where Perl is easier than Python: perl -lane '$F[3] =~ s/, and /, /g if $F[2] =~ /\Afoos?\z/; print "$F[1] $F[4]" if ", $F[3], " =~ /, oats, peas, /' So here's the Python version; it's not necessarily more code but you can't just type it on the command line. Python 3.7 additionally has f-strings which would clean this up a bit more. """ import sys for line in sys.stdin: f = line.split() if f[2] in ('foo', 'foos'): f[3] = f[3].replace(', and ', ', ') if ', oats, peas ,' in ', ' + f[3] + ', ': print(f[1], f[4])