import string


def MakeValidFieldName(header):
  """Turn a header name into a valid bigquery field name.

  https://developers.google.com/bigquery/docs/tables

  Field names are any combination of uppercase and/or lowercase
  letters (A-Z, a-z), digits (0-9) and underscores, but no spaces. The
  first character must be a letter.

  Args:
    header: the possible header value
  Returns:
    a sanitized version of header with only letters, digits or _
    If the result doesn't start with a letter it's prefixed with col_
    This could return an empty string if header has no valid characters.
  """
  valid_chars = string.ascii_letters + string.digits + '_'
  header = ''.join(x in valid_chars and x or '_' for x in header)
  header = header.strip('_')
  while '__' in header:
    header = header.replace('__', '_')
  if header and header[0] not in string.ascii_letters:
    header = 'col_' + header
  return header