NumPy char.center() 函式



NumPy 的char.center()函式用於將字串陣列的元素居中。此函式使用指定的字元填充字串以達到給定的寬度,以便原始字串居中在新字串的指定寬度內。

此函式採用引數,即輸入陣列、寬度和填充字元。

此函式對於格式化字串以在特定寬度內視覺對齊它們很有用,這對於建立表格或對齊文字輸出特別方便。

語法

以下是 NumPy char.center() 函式的語法:

numpy.char.center(a, width, fillchar=' ')

引數

以下是 NumPy char.center() 函式的引數:

  • a(類陣列):這是結果字串的總寬度。如果指定的寬度小於或等於原始字串的長度,則不新增填充。

  • width(int):一個整數,指定陣列中每個字串重複的次數。

  • fillchar(str, 可選):用於填充字串的字元。預設值為空格 (' ')。

返回值

此函式返回一個與輸入陣列形狀相同的陣列,其中每個元素都是輸入陣列中對應元素的居中版本。

示例 1

以下是 NumPy char.center() 函式的基本示例。在此示例中,我們使用預設值 (' ') 作為 fillchar 引數:

import numpy as np

# Define an array of strings
a = np.array(['cat', 'dog', 'elephant'])

# Center each string in a field of width 10, using spaces as the fill character
result = np.char.center(a, 10)
print(result)

以下是 numpy.char.center() 函式基本示例的輸出:

['   cat    ' '   dog    ' ' elephant ']

示例 2

在此示例中,我們將展示如何使用char.center()函式在使用不同填充字元而不是預設空格的指定寬度內居中字串。這對於以視覺上不同的方式格式化字串很有用:

import numpy as np

# Define an array of strings
a = np.array(['cat', 'dog', 'elephant'])

# Center each string in a field of width 10, using '*' as the fill character
result = np.char.center(a, 10, fillchar='*')
print(result)

以下是上述示例的輸出:

['***cat****' '***dog****' '*elephant*']

示例 3

這是一個示例,它展示瞭如何使用指定的寬度和自定義填充字元將陣列中的單個字串居中:

import numpy as np

# Define a single string
a = np.array(['hello'])

# Center the string in a field of width 11, using '-' as the fill character
result = np.char.center(a, 11, fillchar='-')
print(result)

以下是居中單個字串的輸出:

['---hello---']
numpy_string_functions.htm
廣告