<p>Pretty similar to <a href="https://stackoverflow.com/questions/18576943/convert-any-string-to-a-valid-dns-subdomain">Convert any string to a valid DNS subdomain</a>, 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.</p>
<p>Kubernetes <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names" rel="nofollow noreferrer">requires that resource names be a valid DNS subdomain</a>.</p>
<p>I'm looking for something that more or less does:</p>
<ul>
<li>Converts all uppercase to lowercase</li>
<li>Replaces all invalid characters with something valid (e.g. <code>.</code> or <code>-</code>)</li>
<li>Chops invalid characters off the end</li>
</ul>
<p>So for example:</p>
<pre><code>import awesomelibrary
input = 'Inv@l^d_Stuff$.-'
output = awesomelibrary.convert_to_rfc1123_compliant(input)
print(output)
</code></pre>
<p>Expected output:</p>
<pre><code>inv-l-d-stuff
</code></pre>

stevetu21
<p>Essentially this gets it done:</p>
<pre><code>re.sub(r'[^a-zA-Z0-9]+', '-', input).lower()
</code></pre>
