# How to convert string to hex in python

Hi guys. Today in this tutorial we will learn about How to convert string to hex in python. Here we learn to convert string into hexadecimal values. These values are based of 16. And the string of hex are prefixed with 0x. Here i am giving you some methods by using if them you can convert a string to hex easily. So lets learn about of this by given below methods. I hope you guys like it. Lets learn this:

## How to convert string to hex in python

1. string to hex in python

to convert string to hex in python just Use encode(). By using encode() you can convert a string to hex values. First of all we will convert a string into the byte type object by using encode() and after it by using of hex() function you can convert these byte type object into hex values. Lets learn about of this by given below example. I hope you guys like it. `mystr= 'My string'.encode('utf-8') print(mystr.hex())` Output : `4d7920737472696e67`

2. How to convert string to hex in python

to convert string to hex in python just Use hex(). Hex() function is useful for to convert the decimal integer value into the hex values. For this first of all take a integer number and then print it with the hex() function. It will conver it to hex values. Lets learn this by given below example. `num = 102 print(hex(num)) num = 111 print(hex(num)) num = 254 print(hex(num))` Output : `0x66 0x6f 0xfe`

## Method 1: Use encode()

By using encode() you can convert a string to hex values. First of all we will convert a string into the byte type object by using encode() and after it by using of hex() function you can convert these byte type object into hex values. Lets learn about of this by given below example. I hope you guys like it.

``````mystr= 'My string'.encode('utf-8')
print(mystr.hex())``````

Output :

``4d7920737472696e67``

## Method 2: Use hex()

Hex() function is useful for to convert the decimal integer value into the hex values. For this first of all take a integer number and then print it with the hex() function. It will conver it to hex values. Lets learn this by given below example.

``````num = 102
print(hex(num))

num = 111
print(hex(num))

num = 254
print(hex(num))``````

Output :

``````0x66
0x6f
0xfe``````

## Method 3: Use hex() and float()

You can use hex() function and the float() function to convert a floating point number into the hex values. Here you have to use both the functions and you can get the hex values. This method is quite similar to above method which convert the integer number to hex and this is for to convert the float into the hex. So lets learn about of this by given below example.

``````num = 254.52
print(float.hex(num))

num = 587.21
print(float.hex(num))

num = 53.25
print(float.hex(num))``````

Output :

``````0x1.fd0a3d70a3d71p+7
0x1.259ae147ae148p+9
0x1.aa00000000000p+5``````

## Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.