NumPy strings.title()

The numpy.strings.title() function returns the title-cased version of each string in an array. Title case means that each word starts with an uppercase letter, and all other characters are converted to lowercase.

Syntax

</>
Copy
numpy.strings.title(a)

Parameters

ParameterTypeDescription
aarray-like, with StringDType, bytes_, or str_ dtypeInput array containing strings that need to be title-cased.

Return Value

Returns an ndarray containing the title-cased version of each string in the input array.


Examples

1. Title-Casing a Single Word

In this example, we will take a single word in lowercase, and convert this lowercase word to title case.

</>
Copy
import numpy as np

# Define a single word in an array
word = np.array(['apple'], dtype='U')

# Apply title-casing
result = np.strings.title(word)

# Print the result
print("Title-cased word:", result)

Output:

Title-cased word: ['Apple']

2. Title-Casing Multiple Words in an Array

In this example, we will take an array of strings where each string is a word in lowercase, and convert these lowercase words to title case.

</>
Copy
import numpy as np

# Define an array of words
words = np.array(['apple', 'banana', 'cherry'], dtype='U')

# Apply title-casing
title_cased_words = np.strings.title(words)

# Print the results
print("Original words:", words)
print("Title-cased words:", title_cased_words)

Output:

Original words: ['apple' 'banana' 'cherry']
Title-cased words: ['Apple' 'Banana' 'Cherry']

3. Title-Casing Strings with Multiple Words

In this example, we will take an array of strings, where each string contains multiple words in lowercase, and convert these strings to title case.

</>
Copy
import numpy as np

# Define an array of phrases
phrases = np.array(['green apple', 'yellow banana', 'red cherry'], dtype='U')

# Apply title-casing
title_cased_phrases = np.strings.title(phrases)

# Print the results
print("Original phrases:", phrases)
print("Title-cased phrases:", title_cased_phrases)

Output:

Original phrases: ['green apple' 'yellow banana' 'red cherry']
Title-cased phrases: ['Green Apple' 'Yellow Banana' 'Red Cherry']

4. Title-Casing Strings with Mixed Cases

In this example, we will take an array of strings, where each string contains a single word in mixed cases, and convert these strings to title case.

</>
Copy
import numpy as np

# Define an array with mixed case words
mixed_case_words = np.array(['ApPlE', 'BANANA', 'ChErRy'], dtype='U')

# Apply title-casing
title_cased_mixed = np.strings.title(mixed_case_words)

# Print the results
print("Original words:", mixed_case_words)
print("Title-cased words:", title_cased_mixed)

Output:

Original words: ['ApPlE' 'BANANA' 'ChErRy']
Title-cased words: ['Apple' 'Banana' 'Cherry']