title: How can I base64 encode using a custom letter set?
body: <p>I am trying to base64 encode using a custom character set in python3. Most of the examples I have seen in SO are related to Python 2, so I had to make some minor adjustments to the code. The issue that I am facing is that I am replacing the character <code>/</code> with <code>_</code>, but it is still printing with <code>/</code>. My code is: This is just an example, i am not trying to only base64 with urlsafe chars. <code>custom</code> could be anything with the correct length. </p>
  
  <pre class="lang-py prettyprint-override"><code>import base64
  
  data = 'some random? data'
  print(base64.b64encode(data.encode()))
  
  std_base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  custom = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
  
  data = data.translate(str.maketrans(custom, std_base64chars)).encode()
  
  print(base64.b64encode(data))
  
  # Both prints
  b'c29tZSByYW5kb20/IGRhdGE='
  b'c29tZSByYW5kb20/IGRhdGE='
  </code></pre>
  
  <p>How can I get the translation to work so that occurrences of <code>/</code> are replaced correctly with <code>_</code>?</p>
  
  <h2>Edit</h2>
  
  <p>I should make it clear that I am not trying to do only one type of base64 encoding here like urlsafe, but any possible character set. This will be a function were a user can pass their own charset. I am looking for a character by character mapping, not string slicing.</p>
  
  <h2>Edit</h2>
  
  <p>Because there is some confusion around the clarity of my question, I am try to add more details. </p>
  
  <p>I am trying to write a function that can take an arbitrary charset from a user, and then map them individually before base64 encoding. Most of the answers have been around manipulating <code>altchars</code> or string slice and replace, but that doesnt solve all the needs. </p>
  
  <p>So for example, the itoa64 charset is:
  <code>./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=</code> or unix crypt format is <code>./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz</code>. The answers although correct, does not address these situations.  </p>