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

</>
Copy
numpy.strings.expandtabs(a, tabsize=8)

Parameters

ParameterTypeDescription
aarray-like, with StringDType, bytes_, or str_ dtypeInput array of strings containing tab characters.
tabsizeint, optionalNumber 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).

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.