NumPy: String Operations
Last updated: 2026-08-26
1. What You'll Learn
- ❶ Vectorized string methods:
np.char.upper,np.char.lower, etc. - ❷ Pattern matching with
np.char.find,np.char.count - ❸ String joining, splitting, and padding
- ❹ When to use NumPy strings vs Python strings
2. Key Concepts
PYTHON
import numpy as np
names = np.array(['alice', 'bob', 'charlie'])
# Vectorized string operations
print(np.char.upper(names)) # ['ALICE' 'BOB' 'CHARLIE']
print(np.char.capitalize(names)) # ['Alice' 'Bob' 'Charlie']
print(np.char.title(names)) # ['Alice' 'Bob' 'Charlie']
# Pattern matching
print(np.char.find(names, 'li')) # [ 2 -1 3]
print(np.char.count(names, 'e')) # [1 0 1]
# Join and split
print(np.char.join('-', names)) # ['a-l-i-c-e' 'b-o-b' 'c-h-a-r-l-i-e']
print(np.char.split(names, 'i')) # [['al', 'ce'], ['bob'], ['charl', 'e']]
TEXT
📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example: Basic string operations (Difficulty ⭐)
PYTHON
import numpy as np
names = np.array(['alice', 'bob', 'charlie', 'diana'])
print("Upper:", np.char.upper(names))
print("Lower:", np.char.lower(names))
print("Capitalize:", np.char.capitalize(names))
print("Title:", np.char.title(names))
print("Swapcase:", np.char.swapcase(names))
Output:
TEXT 📖 Display onlyUpper: ['ALICE' 'BOB' 'CHARLIE' 'DIANA'] Lower: ['alice' 'bob' 'charlie' 'diana'] Capitalize: ['Alice' 'Bob' 'Charlie' 'Diana'] Title: ['Alice' 'Bob' 'Charlie' 'Diana'] Swapcase: ['ALICE' 'BOB' 'CHARLIE' 'DIANA']
▶ Example: Pattern matching in strings (Difficulty ⭐⭐)
PYTHON
import numpy as np
emails = np.array(['alice@work.com', 'bob@home.org', 'charlie@school.edu'])
# Find position of '@'
at_pos = np.char.find(emails, '@')
print("@ positions:", at_pos)
# Count occurrences of 'e'
e_count = np.char.count(emails, 'e')
print("'e' counts:", e_count)
# Check start/end
print("Starts with 'a':", np.char.startswith(emails, 'a'))
print("Ends with '.edu':", np.char.endswith(emails, '.edu'))
Output:
TEXT 📖 Display only@ positions: [5 3 7] 'e' counts: [1 1 2] Starts with 'a': [ True False False] Ends with '.edu': [False False True]
▶ Example: String joining and padding (Difficulty ⭐⭐)
PYTHON
import numpy as np
words = np.array(['hello', 'world', 'numpy'])
# Join characters with separator
print("Join:", np.char.join('-', words))
# Pad strings to fixed width
print("Pad center:\n", np.char.center(words, 10, fillchar='='))
print("Pad left:\n", np.char.ljust(words, 10, fillchar='.'))
print("Pad right:\n", np.char.rjust(words, 10, fillchar='.'))
# Strip whitespace
messy = np.array([' alice ', ' bob ', ' charlie '])
print("Strip:", np.char.strip(messy))
Output:
TEXT 📖 Display onlyJoin: ['h-e-l-l-o' 'w-o-r-l-d' 'n-u-m-p-y'] Pad center: ['==hello===' '==world====' '==numpy===='] Pad left: ['hello.....' 'world.....' 'numpy.....'] Pad right: ['.....hello' '.....world' '.....numpy'] Strip: ['alice' 'bob' 'charlie']
Q Are NumPy string operations faster than Python loops?
A Yes, for large arrays — the C-level vectorization is much faster than iterating through Python strings. But for single strings, Python's native methods are simpler.
Q What's the dtype for string arrays?
A
np.str_ (or 'U' for Unicode). String arrays have a fixed maximum length, which determines memory usage. Variable-length strings use object dtype.Q Can I use regular expressions?
A NumPy doesn't have native regex support. Use
np.vectorize(re.search) or Pandas .str.contains() for regex operations on arrays.❓ FAQ
Q What is the most important thing to remember?
A NumPy operations are vectorized — avoid Python loops for better performance.
Q Where can I learn more?
A Check the official NumPy documentation at numpy.org for detailed references and advanced topics.
Q Does this work with NumPy 2.x?
A Yes — all examples are compatible with NumPy 2.x. Some older APIs (like np.random.seed) are still supported but the modern alternatives are recommended.
📖 Summary
np.charmodule provides vectorized string operations: upper, lower, capitalize, title- Pattern matching:
find,count,startswith,endswith - Join, split, strip, pad, replace — all vectorized
- String arrays have fixed-width dtype (
U{n}) — memory is pre-allocated - For complex string operations, consider Pandas
.straccessor
📝 Exercises
-
Beginner (Difficulty ⭐): Create an array of 5 names. Apply
upper,lower,capitalize, andtitleto all elements. -
Intermediate (Difficulty ⭐⭐): Create an array of email addresses. Use
np.char.findto find the position of '@' in each email. Then usenp.char.splitto extract the domain part. -
Advanced (Difficulty ⭐⭐⭐): Create an array of 1000 random strings. Benchmark
np.char.upperagainst a Python list comprehension. Record the speedup factor.