NumPy: String Operations

Last updated: 2026-08-26

1. What You'll Learn



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 only
Upper: ['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 only
Join: ['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



📝 Exercises

  1. Beginner (Difficulty ⭐): Create an array of 5 names. Apply upper, lower, capitalize, and title to all elements.

  2. Intermediate (Difficulty ⭐⭐): Create an array of email addresses. Use np.char.find to find the position of '@' in each email. Then use np.char.split to extract the domain part.

  3. Advanced (Difficulty ⭐⭐⭐): Create an array of 1000 random strings. Benchmark np.char.upper against a Python list comprehension. Record the speedup factor.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏