在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個空格:

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

示例

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))

輸出

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

更新於:2022年2月17日

89次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告