Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace tab characters by a fixed tabsize in a string array in Numpy
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...
",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 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("
Result (expand tabs)...
",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...
",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 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("
Result (expand tabs)...
",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']