title: Convert string to hexadecimal with "0x" and leading 0s in Python
body: <p>I want to change a registry key value via Python. The value type will be <code>REG_DWORD</code> which means hexadecimal including <code>0x000</code> in integer format. I am having trouble converting a string with a number to its hexadecimal format in integer.</p>
  <p>Since I am looping through a number of registry keys, my code to change a certain key is as follows:</p>
  <pre><code>for i in range(len(checking_names)): #loop through names to check 
      if checking_names(i) !== should_values(i): #no match
          with winreg.CreateKeyEx(key, subkey_path, 0, winreg.KEY_ALL_ACCESS) as subkey: 
              winreg.DeleteValue(subkey, names_data[i]) #have to delete name in order to overwrite
              winreg.SetValueEx(subkey, names_data[i], 0, winreg.REG_DWORD, new_hex_value) #overwrite name value with correct value from predefined list 
  </code></pre>
  <p>My <code>values_data</code> list is comprised of predefined variables as strings. One of the entries is a string <code>'9600'</code>. In my above code, <code>values_data[i]</code> should be 9600 in hexadecimal format: <code>0x00002580</code>. For this conversion I do the following:</p>
  <pre><code>dec_to_hex_str = format(int(values_data[i]),'x') #string decimal to string hexadecimal conversion
  zeros_pre_x    = '0x' #0x for format 0xffffffff
  
  zeros_to_add   = 8 - len(dec_to_hex_str) #count number of leading 0s to add
  mid_zeros_list = []
  for j in range(zeros_to_add):  
      mid_zeros_list.append(0) #add a leading 0
  mid_zeros = ''.join(mid_zeros_list) #convert list to string
  
  new_hex_value = int(zeros_pre_hex + mid_zeros + dec_to_hex_str)
  </code></pre>
  <p>When I run this code, my Python shell is unresponsive, and there is no change in the Windows registry for the <code>subkey</code> value. The problem seems to be, that <code>winreg.SetValueEx .... winreg.REG_DWORD</code> only understands integer format but my <code>new_hex_value</code> is not being properly converted from string to integer.</p>
  <p>Any help would be appreciated!</p>