在 NumPy 字串陣列中用固定制表符大小替換製表符
要在字串陣列中用固定制表符大小替換製表符,請使用 Python NumPy 中的 **numpy.char.expandtabs()** 方法。“**tabsize**”引數用於將製表符替換為 tabsize 個空格。如果未給出,則預設為 8 個空格。
expandtabs() 函式返回每個字串元素的副本,其中所有制表符都替換為一個或多個空格,具體取決於當前列和給定的 tabsize。在字串中出現每個換行符後,列號將重置為零。它不理解其他非列印字元或轉義序列。
numpy.char 模組為 numpy.str_ 或 numpy.bytes_ 型別陣列提供了一組向量化字串操作。
步驟
首先,匯入所需的庫:
import numpy as np
建立一個一維字串陣列:
arr = np.array(['Bella\tCio', 'Tom\tHanks', 'Monry\tHeist\tSeries'])
顯示我們的陣列:
print("Array...
",arr)獲取資料型別:
print("
Array datatype...
",arr.dtype)
獲取陣列的維度:
print("
Array Dimensions...
",arr.ndim)獲取陣列的形狀:
print("
Our Array Shape...
",arr.shape)
獲取陣列的元素數量:
print("
Elements in the Array...
",arr.size)要使用固定制表符大小替換字串陣列中的製表符,請使用 numpy.char.expandtabs() 方法。“tabsize”引數用於將製表符替換為 tabsize 個空格。如果未給出,則預設為 8 個空格。我們將“tabsize”設定為 10,即 10 個空格:
print("
Result (expand tabs)...
",np.char.expandtabs(arr, tabsize = 10))
示例
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))輸出
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']
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP