NumPy strings.encode()
The numpy.strings.encode() function encodes an array of strings element-wise using the specified encoding format.
It is useful for converting string data into encoded byte representations.
Syntax
</>
Copy
numpy.strings.encode(a, encoding=None, errors=None)
Parameters
| Parameter | Type | Description |
|---|---|---|
a | array_like | An array of strings with StringDType or str_ dtype to be encoded. |
encoding | str, optional | The encoding format to use, such as 'utf-8' or 'ascii'. If not provided, the default system encoding is used. |
errors | str, optional | Specifies how to handle encoding errors. Common values are 'strict', 'ignore', and 'replace'. |
Return Value
Returns an ndarray where each element is the encoded byte representation of the corresponding string in the input array.
Examples
1. Encoding a Single String
In this example, we encode a single string into UTF-8 format.
</>
Copy
import numpy as np
# Define a string
fruit = np.array("apple", dtype="str")
# Encode the string using UTF-8
encoded_fruit = np.strings.encode(fruit, encoding="utf-8")
# Print the encoded result
print("Encoded string:", encoded_fruit)
Output:
Encoded string: np.bytes_(b'apple')
