O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Performing string operations with chararray

NumPy has a specialized chararray object that holds strings. It is a subclass of ndarray and has special string methods. We will download text from the Python website and use those methods. The advantages of chararray over a normal array of strings are as follows:

  • Whitespace of array elements is automatically trimmed on indexing
  • Whitespace at the ends of strings is also trimmed by comparison operators
  • Vectorized string operations are available, so loops are not needed

How to do it...

Let's create the character array:

  1. Create the character array as a view:
    carray = np.array(html).view(np.chararray)
  2. Expand tabs to spaces with the expandtabs() function. This function accepts the tab size as an argument. The value ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required