0

Pretty similar to Convert any string to a valid DNS subdomain, except asking it for Python (I'm using 3.10) and (sort of) Kubernetes. Hoping to accomplish this in the most pythonic (i.e. just grab a library that someone else wrote) way possible.

Kubernetes requires that resource names be a valid DNS subdomain.

I'm looking for something that more or less does:

  • Converts all uppercase to lowercase
  • Replaces all invalid characters with something valid (e.g. . or -)
  • Chops invalid characters off the end

So for example:

import awesomelibrary
input = 'Inv@l^d_Stuff$.-'
output = awesomelibrary.convert_to_rfc1123_compliant(input)
print(output)

Expected output:

inv-l-d-stuff
stevetu21
  • 160
  • 1
  • 8
  • There are built-in functions that will accomplish the same goal https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python – msanford May 26 '22 at 16:51

1 Answers1

1

Essentially this gets it done:

re.sub(r'[^a-zA-Z0-9]+', '-', input).lower()
stevetu21
  • 160
  • 1
  • 8