Return a copy of each string element where all tab characters are replaced by spaces in Numpy


To return a copy of each string element where all tab characters are replaced by spaces, use the numpy.char.expandtabs() method in Python Numpy. We can also set the "tabsize" parameter i.e. 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...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Elements in the Array...
",arr.size)

To return a copy of each string element where all tab characters are replaced by spaces, use the numpy.char.expandtabs() method. We can also set the "tabsize" parameter i.e. replace tabs with tabsize number of spaces. If not given defaults to 8 spaces −

print("
Result (expand tabs)...
",np.char.expandtabs(arr))

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...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To return a copy of each string element where all tab characters are replaced by spaces, use the numpy.char.expandtabs() method in Python Numpy # We can also set the "tabsize" parameter i.e. replace tabs with tabsize number of spaces. If not given defaults to 8 spaces. print("
Result (expand tabs)...
",np.char.expandtabs(arr))

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']

Updated on: 17-Feb-2022

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements