polars.Series.str.head#

Series.str.head(n: int | IntoExprColumn) Series[source]#

Return the first n characters of each string in a String Series.

Parameters:
n

Length of the slice (integer or expression). Negative indexing is supported; see note (2) below.

Returns:
Series

Series of data type String.

Notes

  1. The n input is defined in terms of the number of characters in the (UTF8) string. A character is defined as a Unicode scalar value. A single character is represented by a single byte when working with ASCII text, and a maximum of 4 bytes otherwise.

  2. When n is negative, head returns characters up to the n`th from the end of the string. For example, if `n = -3, then all characters except the last three are returned.

  3. If the length of the string has fewer than n characters, the full string is returned.

Examples

Return up to the first 5 characters.

>>> s = pl.Series(["pear", None, "papaya", "dragonfruit"])
>>> s.str.head(5)
shape: (4,)
Series: '' [str]
[
    "pear"
    null
    "papay"
    "drago"
]

Return up to the 3rd character from the end.

>>> s = pl.Series(["pear", None, "papaya", "dragonfruit"])
>>> s.str.head(-3)
shape: (4,)
Series: '' [str]
[
    "p"
    null
    "pap"
    "dragonfr"
]