--- ./doc/examples/sample_opal_scripts/FimoClient.py	(original)
+++ ./doc/examples/sample_opal_scripts/FimoClient.py	(refactored)
@@ -13,7 +13,7 @@
 from os import mkdir
 from subprocess import call
 from time import sleep
-from urlparse import urlparse
+from urllib.parse import urlparse
 from ZSI.TC import String
 
 
@@ -67,35 +67,35 @@
 req._inputFile = inputFiles
 
 # Launch a non-blocking job
-print "Launching non-blocking FIMO job"
+print("Launching non-blocking FIMO job")
 resp = appServicePort.launchJob(req)
 jobID = resp._jobID
-print "Received Job ID:", jobID
+print("Received Job ID:", jobID)
 
 # Poll for job status
 status = resp._status
-print "Polling job status"
+print("Polling job status")
 while 1:
   # print current status
-  print "Status:"
-  print "\tCode:", status._code
-  print "\tMessage:", status._message
-  print "\tOutput Base URL:", status._baseURL
+  print("Status:")
+  print("\tCode:", status._code)
+  print("\tMessage:", status._message)
+  print("\tOutput Base URL:", status._baseURL)
 
   if (status._code == 8) or (status._code == 4): # STATUS_DONE || STATUS_FAILED
     break
 
-  print "Waiting 30 seconds"
+  print("Waiting 30 seconds")
   sleep(30)
   
   # Query job status
   status = appServicePort.queryStatus(queryStatusRequest(jobID))
 
 if status._code == 8: # 8 = GramJob.STATUS_DONE
-  print "\nDownloading Outputs (using wget):\n\n";
+  print("\nDownloading Outputs (using wget):\n\n");
   output_dir = 'fimo_out'
-  dir_count = sum(1 for _ in filter(None, urlparse(status._baseURL).path.split("/")))
+  dir_count = sum(1 for _ in [_f for _f in urlparse(status._baseURL).path.split("/") if _f])
   index_url = status._baseURL + '/index.html'
   call(["wget", "-r", "-nc", "-p", "-np", "-nH", "--cut-dirs=" + str(dir_count), "-P",  output_dir, index_url])
 
-print "\nJob Complete\n\n";
+print("\nJob Complete\n\n");
--- ./doc/examples/sample_opal_scripts/MemeClient.py	(original)
+++ ./doc/examples/sample_opal_scripts/MemeClient.py	(refactored)
@@ -13,7 +13,7 @@
 from os import mkdir
 from subprocess import call
 from time import sleep
-from urlparse import urlparse
+from urllib.parse import urlparse
 from ZSI.TC import String
 
 # Set the location of our service
@@ -64,35 +64,35 @@
 req._inputFile = inputFiles
 
 # Launch non-blocking job and retrieve job ID
-print "Launching remote MEME job"
+print("Launching remote MEME job")
 resp = appServicePort.launchJob(req)
 jobID = resp._jobID
-print "Received Job ID:", jobID
+print("Received Job ID:", jobID)
 
 # Poll for job status
 status = resp._status
-print "Polling job status"
+print("Polling job status")
 while 1:
   # print current status
-  print "Status:"
-  print "\tCode:", status._code
-  print "\tMessage:", status._message
-  print "\tOutput Base URL:", status._baseURL
+  print("Status:")
+  print("\tCode:", status._code)
+  print("\tMessage:", status._message)
+  print("\tOutput Base URL:", status._baseURL)
 
   if (status._code == 8) or (status._code == 4): # STATUS_DONE || STATUS_FAILED
     break
 
-  print "Waiting 30 seconds"
+  print("Waiting 30 seconds")
   sleep(30)
   
   # Query job status
   status = appServicePort.queryStatus(queryStatusRequest(jobID))
 
 if status._code == 8: # 8 = GramJob.STATUS_DONE
-  print "\nDownloading Outputs (using wget):\n\n";
+  print("\nDownloading Outputs (using wget):\n\n");
   output_dir = 'meme_out'
-  dir_count = sum(1 for _ in filter(None, urlparse(status._baseURL).path.split("/")))
+  dir_count = sum(1 for _ in [_f for _f in urlparse(status._baseURL).path.split("/") if _f])
   index_url = status._baseURL + '/index.html'
   call(["wget", "-r", "-nc", "-p", "-np", "-nH", "--cut-dirs=" + str(dir_count), "-P",  output_dir, index_url])
 
-print "\nJob Complete\n\n";
+print("\nJob Complete\n\n");
--- ./scripts/alphabet.py	(original)
+++ ./scripts/alphabet.py	(refactored)
@@ -1,6 +1,6 @@
 #!@WHICHPYTHON@
 
-from __future__ import with_statement
+
 import collections, itertools, json, math, re, string, sys
 from xml.sax.saxutils import quoteattr
 
@@ -9,7 +9,7 @@
 def alphabetSymbolCompare(x, y):
     """Compares 2 strings of alphabet symbols"""
     if len(x) == len(y):
-        for a, b in itertools.izip(x, y):
+        for a, b in zip(x, y):
             # letters before numbers and symbols
             if a.isalpha():
                 if b.isalpha():
@@ -302,7 +302,7 @@
                 comprise_lookup[sym.comprise].append(sym)
             else:
                 comprise_lookup[sym.comprise] = [sym]
-        for comprise, syms in comprise_lookup.iteritems():
+        for comprise, syms in comprise_lookup.items():
             if len(comprise) == 1:
                 # alias for a core symbol
                 core_sym = self.sym_lookup[comprise]
@@ -356,7 +356,7 @@
         value = 0.4
         step = 360 / ncolours
         colours = []
-        for i in xrange(ncolours):
+        for i in range(ncolours):
             rgb = _hsv2rgb(step * i, sat, value)
             colours.append((rgb, _rgb2lab(rgb)))
         # for each of the unique colours find the closest colour in the generated colours and remove it
@@ -364,8 +364,8 @@
             best_dist = None
             best_i = None
             best_j = None
-            for i in xrange(len(uniques)):
-                for j in xrange(len(colours)):
+            for i in range(len(uniques)):
+                for j in range(len(colours)):
                     dist = _lab_dist(uniques[i], colours[j][1])
                     if best_dist == None or dist < best_dist:
                         best_dist = dist
@@ -448,15 +448,15 @@
         # check assumptions
         if self.parsed:
             raise RuntimeError("Parsing is already done!")
-        if not(isinstance(symbol, basestring) and len(symbol) == 1):
+        if not(isinstance(symbol, str) and len(symbol) == 1):
             raise RuntimeError("Expected symbol to be a single character")
-        if name != None and not(isinstance(name, basestring)):
+        if name != None and not(isinstance(name, str)):
             raise RuntimeError("Expected name to be a string")
-        if colour != None and not(isinstance(colour, (int, long))):
+        if colour != None and not(isinstance(colour, int)):
             raise RuntimeError("Expected colour to be a unsigned 24 bit number")
-        if complement != None and not(isinstance(complement, basestring) and len(complement) == 1):
+        if complement != None and not(isinstance(complement, str) and len(complement) == 1):
             raise RuntimeError("Expected complement symbol to be a single character")
-        if comprise != None and not(isinstance(comprise, basestring)):
+        if comprise != None and not(isinstance(comprise, str)):
             raise RuntimeError("Expected name to be a string")
         if complement != None and comprise != None:
             raise RuntimeError("Expected only comprise or complement not both")
@@ -677,7 +677,7 @@
                 alph_sym_1.complement = alph_sym_2.index
         # link comprising symbols
         # core symbols have themselves in the comprise list
-        for i in xrange(self.ncore):
+        for i in range(self.ncore):
             self.symbols[i].comprise = frozenset([i])
         # ambiguous symbols link to the core symbols
         for sym_obj in reader.ambig_syms:
@@ -701,11 +701,11 @@
             for alph_sym in self.symbols:
               self.comp_symbols[alph_sym.symbol] = self.getComplement(alph_sym.symbol)
         # try to determine a pair of symbols that make up each ambiguous symbol
-        symbols_by_count = [[] for _ in xrange(self.ncore + 1)]
+        symbols_by_count = [[] for _ in range(self.ncore + 1)]
         for alph_sym in self.symbols:
             symbols_by_count[len(alph_sym.comprise)].append(alph_sym)
         for alph_sym in self.symbols[self.ncore:]:
-            for j in xrange(1, len(alph_sym.comprise)):
+            for j in range(1, len(alph_sym.comprise)):
                 for part in symbols_by_count[j]:
                     if not(part.comprise < alph_sym.comprise):
                         continue
@@ -740,7 +740,7 @@
 
     def getColour(self, sym):
         """Get the colour for this symbol"""
-        if isinstance(sym, (int, long)):
+        if isinstance(sym, int):
             if sym < len(self.symbols):
                 return self.symbols[sym].colour
             raise RuntimeError("Symbol index " + sym + " does not exist in alphabet")
@@ -751,7 +751,7 @@
 
     def getMutedColour(self, sym):
         """Get the muted colour for this symbol"""
-        if isinstance(sym, (int, long)):
+        if isinstance(sym, int):
             if sym < len(self.symbols):
                 return _lighten(self.symbols[sym].colour)
             raise RuntimeError("Symbol index " + str(sym) + " does not exist in alphabet")
@@ -807,7 +807,7 @@
 
     def getComprisingIndexes(self, sym):
         """Retrieve the indexes of the comprising core symbols (immutable)"""
-        if isinstance(sym, (int, long)):
+        if isinstance(sym, int):
             if sym < len(self.symbols):
                 return self.symbols[sym].comprise
         else:
@@ -817,7 +817,7 @@
 
     def getPairIndexes(self, sym):
         """Retrieve the indexes of the comprising core symbols (immutable)"""
-        if isinstance(sym, (int, long)):
+        if isinstance(sym, int):
             if sym < len(self.symbols):
                 return self.symbols[sym].pair
         else:
@@ -868,7 +868,7 @@
 
     def getComplementIndex(self, sym):
         """Retrieve the index of the complement of the symbol"""
-        if isinstance(sym, (int, long)):
+        if isinstance(sym, int):
             if sym < len(self.symbols):
                 return self.symbols[sym].complement
         else:
@@ -941,7 +941,7 @@
         """Create the text representation of the alphabet"""
         out = []
         # output core symbols with complements
-        for i in xrange(self.ncore):
+        for i in range(self.ncore):
             sym1 = self.symbols[i]
             # check symbol has a complement (which we assume is symetric)
             if sym1.complement == None:
@@ -954,14 +954,14 @@
             out.append(sym2.asText())
             out.append("\n")
         # output core symbols without complements
-        for i in xrange(self.ncore):
+        for i in range(self.ncore):
             sym = self.symbols[i]
             if sym.complement != None:
                 continue
             out.append(sym.asText())
             out.append("\n")
         # output ambiguous symbols
-        for i in xrange(self.ncore, len(self.symbols)):
+        for i in range(self.ncore, len(self.symbols)):
             sym = self.symbols[i]
             comprise_str = "".join(sorted([self.symbols[symi].symbol for symi in sym.comprise], cmp=alphabetSymbolCompare))
             out.append(sym.asText())
@@ -975,7 +975,7 @@
                     out.append(comprise_str)
                     out.append("\n")
         # output aliases for core symbols
-        for i in xrange(self.ncore):
+        for i in range(self.ncore):
             sym = self.symbols[i]
             if sym.aliases != None:
                 for alias in sym.aliases:
@@ -1139,7 +1139,7 @@
         prime = 0
         alt = 0
         other = 0
-        for sym, count in counts.iteritems():
+        for sym, count in counts.items():
             if alphabet.isCoreSymbol(sym):
                 seen.add(alphabet.getIndex(sym))
                 if alphabet.isPrimeSymbol(sym):
--- ./scripts/hypergeometric.py	(original)
+++ ./scripts/hypergeometric.py	(refactored)
@@ -16,7 +16,7 @@
         psyco_found = False
         pass
     if psyco_found:
-        print >> sys.stderr, "Using psyco..."
+        print("Using psyco...", file=sys.stderr)
 
 # global constants
 _log10 = log(10)
@@ -170,7 +170,7 @@
         return 0.0
 
     key = str(n)
-    if _lnfact_hash.has_key(key):
+    if key in _lnfact_hash:
         return _lnfact_hash[key]
 
     result = lngamm(n+1.0)
@@ -230,29 +230,29 @@
 
     # no arguments: print usage
     if len(sys.argv) == 1:
-        print >> sys.stderr, usage; sys.exit(1)
+        print(usage, file=sys.stderr); sys.exit(1)
 
     # parse command line
     i = 1
     while i < len(sys.argv):
         arg = sys.argv[i]
         if (arg == "-h"):
-            print >> sys.stderr, usage; sys.exit(1)
+            print(usage, file=sys.stderr); sys.exit(1)
         else:
             if (i==1):
                 try: p = string.atoi(sys.argv[i])
-                except: print >> sys.stderr, usage; sys.exit(1)
+                except: print(usage, file=sys.stderr); sys.exit(1)
             elif (i==2):
                 try: P = string.atoi(sys.argv[i])
-                except: print >> sys.stderr, usage; sys.exit(1)
+                except: print(usage, file=sys.stderr); sys.exit(1)
             elif (i==3):
                 try: n = string.atoi(sys.argv[i])
-                except: print >> sys.stderr, usage; sys.exit(1)
+                except: print(usage, file=sys.stderr); sys.exit(1)
             elif (i==4):
                 try: N = string.atoi(sys.argv[i])
-                except: print >> sys.stderr, usage; sys.exit(1)
+                except: print(usage, file=sys.stderr); sys.exit(1)
             else:
-                print >> sys.stderr, usage; sys.exit(1)
+                print(usage, file=sys.stderr); sys.exit(1)
         i += 1
 
     # compute cumulative hypergeometric p-value
@@ -262,7 +262,7 @@
     pvalue = sprint_logx(log_pvalue, 3, "%6.3fe%-5.0f")
     #pvalue2 = sprint_logx(log_less, 3, "%6.3fe%-5.0f")
     #print >> sys.stdout, pvalue, pvalue2, p, P, n, N
-    print >> sys.stdout, pvalue, p, P, n, N
+    print(pvalue, p, P, n, N, file=sys.stdout)
 
     sys.exit(0)
 
--- ./scripts/sequence.py	(original)
+++ ./scripts/sequence.py	(refactored)
@@ -1,6 +1,6 @@
 #!@WHICHPYTHON@
 
-from __future__ import with_statement
+
 import copy, string, sys
 import alphabet
 
@@ -40,7 +40,7 @@
             alpha = alphabet.getBySeq(self.data)
             if alpha == None:
                 raise RuntimeError("Could not identify alphabet from sequence")
-        elif isinstance(alpha, basestring):
+        elif isinstance(alpha, str):
             alphaname = alpha
             alpha = alphabet.getByName(alphaname)
             if alpha == None:
@@ -98,7 +98,7 @@
 
     def nice(self):
         """ A short description of the sequence """
-        print self.getName(), ":", self.getLen()
+        print(self.getName(), ":", self.getLen())
 
 def readStrings(filename):
     """ Read one or more lines of text from a file--for example an alignment.
@@ -131,8 +131,8 @@
                     else:
                         seqnew = Sequence(seqdata, alpha, seqname, seqinfo)
                     seqlist.append(seqnew)
-                except RuntimeError, e:
-                    print >> sys.stderr, "Warning: "+seqname+" is invalid (ignored): ", e
+                except RuntimeError as e:
+                    print("Warning: "+seqname+" is invalid (ignored): ", e, file=sys.stderr)
             seqinfo = thisline[1:-1]         # everything on the defline is "info"
             seqname = seqinfo.split()[0]     # up to first space
             seqdata = []
@@ -149,8 +149,8 @@
             else:
                 seqnew = Sequence(seqdata, alpha, seqname, seqinfo)
             seqlist.append(seqnew)
-        except RuntimeError, e:
-            print >> sys.stderr, "Warning: " + seqname + " is invalid (ignored): ", e
+        except RuntimeError as e:
+            print("Warning: " + seqname + " is invalid (ignored): ", e, file=sys.stderr)
     else:
         raise RuntimeError("No sequences on FASTA format found in this file")
     fh.close()
@@ -177,7 +177,7 @@
             if isinstance(seq, Sequence):
                 _writeOneFASTA(seq, fh)
             else:
-                print >> sys.stderr, "Warning: could not write " + seq.getName() + " (ignored)."
+                print("Warning: could not write " + seq.getName() + " (ignored).", file=sys.stderr)
     fh.flush()
     fh.close()
 
@@ -592,10 +592,10 @@
     pwm = PWM(alpha)
     pwm.setFromAlignment(aln)
     for row in pwm.pretty():
-        print row
+        print(row)
     for s in seqs:
-        print s.getName(), s.getLen(), s.getAlphabet().getSymbols()
+        print(s.getName(), s.getLen(), s.getAlphabet().getSymbols())
         for m in regexp.match( s ):
-            print "pos: %d pat: %s %4.2f" % (m[0], m[1], m[2])
+            print("pos: %d pat: %s %4.2f" % (m[0], m[1], m[2]))
         for m in pwm.match( s ):
-            print "pos: %d pat: %s %4.2f" % (m[0], m[1], m[2])
+            print("pos: %d pat: %s %4.2f" % (m[0], m[1], m[2]))
