NumPy strings.expandtabs()
The numpy.strings.expandtabs()
function replaces tab characters (\t
) in each string element with spaces.
The number of spaces used to replace a tab depends on the specified tab size.
Syntax
numpy.strings.expandtabs(a, tabsize=8)
Parameters
Parameter | Type | Description |
---|---|---|
a | array-like, with StringDType, bytes_, or str_ dtype | Input array of strings containing tab characters. |
tabsize | int, optional | Number of spaces to replace each tab character. Defaults to 8 if not provided. |
Return Value
Returns an array where each string has its tab characters replaced by spaces. The number of spaces depends on the tab size and the current column position.
Examples
1. Replacing Tabs with Default Tab Size
In this example, we replace tab characters in a string using the default tab size (8 spaces).
import numpy as np
# Define a string containing tab characters
text = np.array(["apple\tbanana\tcherry"])
# Replace tabs with default size (8 spaces)
result = np.strings.expandtabs(text)
# Print the result
print(result)
Output:
['apple banana cherry']

2. Using a Custom Tab Size
Here, we specify a custom tab size of 4 spaces instead of the default 8.
import numpy as np
# Define a string containing tab characters
text = np.array(["apple\tbanana\tcherry"])
# Replace tabs with 4 spaces
result = np.strings.expandtabs(text, tabsize=4)
# Print the result
print(result)
Output:
['apple banana cherry']

3. Handling Multiple Tabs in a String
We demonstrate how multiple tab characters affect spacing when replaced.
import numpy as np
# Define a string with multiple tab characters
text = np.array(["apple\t\tbanana\tcherry"])
# Replace tabs with default size (8 spaces)
result = np.strings.expandtabs(text)
# Print the result
print(result)
Output:
['apple banana cherry']

The extra tab between apple
and banana
causes additional spacing due to alignment based on an 8-space tab width.
4. Expanding Tabs in a Multi-line String
The column count resets after a newline, affecting tab alignment in multi-line strings.
import numpy as np
# Define a multi-line string with tabs
text = np.array(["apple\tbanana\ncherry\tdate"])
# Replace tabs with 6 spaces
result = np.strings.expandtabs(text, tabsize=6)
# Print the result
print(result)
Output:
['apple banana\ncherry date']

Note that after the newline, the tab spacing resets, affecting alignment differently on each line.