Replace tab characters by a fixed tabsize in a string array in Numpy

NumpyServer Side ProgrammingProgramming

To replace tab characters by a fixed tabsize in a string array, use the numpy.char.expandtabs() method in Python Numpy. The "tabsize" parameter is used to replace tabs with tabsize number of spaces. If not given defaults to 8 spaces.

The function expandtabs() returns a copy of each string element where all tab characters are replaced by one or more spaces, depending on the current column and the given tabsize. The column number is reset to zero after each newline occurring in the string. This doesn’t understand other non-printing characters or escape sequences.

The numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_ or numpy.bytes_.

Steps

At first, import the required library −

import numpy as np

Create a One-Dimensional array of string −

arr = np.array(['Bella\tCio', 'Tom\tHanks', 'Monry\tHeist\tSeries'])

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...\n",arr.size)

To replace tab characters by a fixed tabsize in a string array, use the numpy.char.expandtabs() method. The "tabsize" parameter is used to replace tabs with tabsize number of spaces. If not given defaults to 8 spaces. We have set the "tabsize" to 10 i.e. 10 spaces −

print("\nResult (expand tabs)...\n",np.char.expandtabs(arr, tabsize = 10))

Example

import numpy as np

# Create a One-Dimensional array of string
arr = np.array(['Bella\tCio', 'Tom\tHanks', 'Monry\tHeist\tSeries'])

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nElements in the Array...\n",arr.size)

# To replace tab characters by a fixed tabsize in a string array, use the numpy.char.expandtabs() method in Python Numpy

# The "tabsize" parameter is used to replace tabs with tabsize number of spaces. If not given defaults to 8 spaces.
# We have set the "tabsize" to 10 i.e. 10 spaces
print("\nResult (expand tabs)...\n",np.char.expandtabs(arr, tabsize =
10))

Output

Array...
['Bella\tCio' 'Tom\tHanks' 'Monry\tHeist\tSeries']

Array datatype...
<U18

Array Dimensions...
1

Our Array Shape...
(3,)

Elements in the Array...
3

Result (expand tabs)...
['Bella Cio' 'Tom Hanks' 'Monry Heist Series']
raja
Updated on 17-Feb-2022 11:07:48

Advertisements