---
title: "Best way to convert string to bytes in Python with example ?"  
description: "Best way to convert string to bytes in Python with example ?"  
author: "Erick Wilsom"  
published: 2022-10-27  
updated: 2023-04-06  
canonical: https://www.mindstick.com/forum/157174/best-way-to-convert-string-to-bytes-in-python-with-example  
category: "python"  
tags: ["python", "python-3.x"]  
reading_time: 2 minutes  

---

# Best way to convert string to bytes in Python with example ?

Which [method](https://www.mindstick.com/forum/166/webservice-method) is more Pythonic?\

## Replies

### Reply by Aryan Kumar

The best and short way to convert a user input string to bytes is “**encode()**” method.\

## Code:-

```python
Str1 = input("Enter a String: ")
byt_obj = Str1.encode("utf-8")
print(byt_obj)
print(type(byt_obj))
```

the **encode()** method on the **string** variable with the argument **'utf-8'** to convert it to bytes. The resulting bytes object is assigned to the **byt_obj** variable.

### Reply by Krishnapriya Rajeev

There are various methods in python to convert a string to a byte array.

One of the best methods for this task is to use ***string_name.encode(encoding).***

It is implemented in the following code:

```plaintext
string = "Welcome to Mindstick Forum"
#converting string to byte
byte_array = string.encode()
print("The byte converted string is  : " + str(byte_array) + ", type : " + str(type(byte_array)))

OUTPUT:
The byte converted string is  : b'Welcome to Mindstick Forum', type : <class 'bytes'>
```

Here, the ***encode()*** function is used to convert the string to a byte.

We can also use***bytes()*** function for the same but *encode()* is more efficient as it can be called *directly on a string object*. We can skip a level of indirection by not using *bytes()* which points to CPython Library and then implicitly calls *encode()* for encoding the string.

The default encoding of *encode()* is ‘utf-8’ and you don't have to include it in the code if that's the encoding you want to use. Otherwise, you have to explicitly specify the encoding.


---

Original Source: https://www.mindstick.com/forum/157174/best-way-to-convert-string-to-bytes-in-python-with-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
