NumPy strings.swapcase()

The numpy.strings.swapcase() function returns an element-wise copy of the input string with uppercase characters converted to lowercase and vice versa.

Syntax

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

Parameters

ParameterTypeDescription
aarray-like (StringDType, bytes_, or str_ dtype)Input array containing strings.

Return Value

Returns an ndarray with the same type as the input, where all uppercase characters are converted to lowercase and vice versa.


Examples

1. Swapping Case for a Single String

In this example, we will convert uppercase letters to lowercase and lowercase letters to uppercase for a single string.

</>
Copy
import numpy as np

# Define a string
word = np.str_("Apple")

# Apply swapcase()
result = np.strings.swapcase(word)

# Print the result
print("Original:", word)
print("Swapped Case:", result)

Output:

Original: Apple
Swapped Case: aPPLE

2. Swapping Case for an Array of Strings

In this example, we will convert the case for multiple string elements in an array.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(["Apple", "Banana", "Cherry"], dtype="U")

# Apply swapcase() to each element
swapped_fruits = np.strings.swapcase(fruits)

# Print the results
print("Original:", fruits)
print("Swapped Case:", swapped_fruits)

Output:

Original: ['Apple' 'Banana' 'Cherry']
Swapped Case: ['aPPLE' 'bANANA' 'cHERRY']

3. Swapping Case with Mixed Case Strings

In this example, we will show how mixed uppercase and lowercase letters are swapped.

</>
Copy
import numpy as np

# Define an array of mixed-case strings
words = np.array(["PyThOn", "NuMPy", "CoDinG"], dtype="U")

# Apply swapcase()
swapped_words = np.strings.swapcase(words)

# Print the results
print("Original:", words)
print("Swapped Case:", swapped_words)

Output:

Original: ['PyThOn' 'NuMPy' 'CoDinG']
Swapped Case: ['pYtHoN' 'nUmpY' 'cOdINg']