Skip to content

narwhals.Series.str

contains(pattern: str, *, literal: bool = False) -> SeriesT

Check if string contains a substring that matches a pattern.

Parameters:

Name Type Description Default
pattern str

A Character sequence or valid regular expression pattern.

required
literal bool

If True, treats the pattern as a literal string. If False, assumes the pattern is a regular expression.

False

Returns:

Type Description
SeriesT

A new Series with boolean values indicating if each string contains the pattern.

Examples:

>>> import pyarrow as pa
>>> import narwhals as nw
>>> s_native = pa.chunked_array([["cat", "dog", "rabbit and parrot"]])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.contains("cat|parrot").to_native()
<pyarrow.lib.ChunkedArray object at ...>
[
  [
    true,
    false,
    true
  ]
]

ends_with(suffix: str) -> SeriesT

Check if string values end with a substring.

Parameters:

Name Type Description Default
suffix str

suffix substring

required

Returns:

Type Description
SeriesT

A new Series with boolean values indicating if each string ends with the suffix.

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["apple", "mango", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.ends_with("ngo").to_native()
0    False
1     True
2     None
dtype: object

head(n: int = 5) -> SeriesT

Take the first n elements of each string.

Parameters:

Name Type Description Default
n int

Number of elements to take. Negative indexing is supported (see note (1.))

5

Returns:

Type Description
SeriesT

A new Series containing the first n characters of each string.

Notes
  1. When the n input 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.
  2. If the length of the string has fewer than n characters, the full string is returned.

Examples:

>>> import pyarrow as pa
>>> import narwhals as nw
>>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.head().to_native()
<pyarrow.lib.ChunkedArray object at ...>
[
  [
    "taata",
    "taata",
    "zukky"
  ]
]

len_chars() -> SeriesT

Return the length of each string as the number of characters.

Returns:

Type Description
SeriesT

A new Series containing the length of each string in characters.

Examples:

>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["foo", "345", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.len_chars().to_native()
shape: (3,)
Series: '' [u32]
[
        3
        3
        null
]

replace(pattern: str, value: str, *, literal: bool = False, n: int = 1) -> SeriesT

Replace first matching regex/literal substring with a new string value.

Parameters:

Name Type Description Default
pattern str

A valid regular expression pattern.

required
value str

String that will replace the matched substring.

required
literal bool

Treat pattern as a literal string.

False
n int

Number of matches to replace.

1

Returns:

Type Description
SeriesT

A new Series with the regex/literal pattern replaced with the specified value.

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["123abc", "abc abc123"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.replace("abc", "").to_native()
0        123
1     abc123
dtype: object

replace_all(pattern: str, value: str, *, literal: bool = False) -> SeriesT

Replace all matching regex/literal substring with a new string value.

Parameters:

Name Type Description Default
pattern str

A valid regular expression pattern.

required
value str

String that will replace the matched substring.

required
literal bool

Treat pattern as a literal string.

False

Returns:

Type Description
SeriesT

A new Series with all occurrences of pattern replaced with the specified value.

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["123abc", "abc abc123"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.replace_all("abc", "").to_native()
0     123
1     123
dtype: object

slice(offset: int, length: int | None = None) -> SeriesT

Create subslices of the string values of a Series.

Parameters:

Name Type Description Default
offset int

Start index. Negative indexing is supported.

required
length int | None

Length of the slice. If set to None (default), the slice is taken to the end of the string.

None

Returns:

Type Description
SeriesT

A new Series containing subslices of each string.

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["pear", None, "papaya"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.slice(4, 3).to_native()
0
1    None
2      ya
dtype: object

split(by: str) -> SeriesT

Split the string values of a Series by a substring.

Parameters:

Name Type Description Default
by str

Substring to split by.

required

Returns:

Type Description
SeriesT

A new Series containing lists of strings.

Examples:

>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["foo bar", "foo_bar"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.split("_").to_native()
shape: (2,)
Series: '' [list[str]]
[
        ["foo bar"]
        ["foo", "bar"]
]

starts_with(prefix: str) -> SeriesT

Check if string values start with a substring.

Parameters:

Name Type Description Default
prefix str

prefix substring

required

Returns:

Type Description
SeriesT

A new Series with boolean values indicating if each string starts with the prefix.

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["apple", "mango", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.starts_with("app").to_native()
0     True
1    False
2     None
dtype: object

strip_chars(characters: str | None = None) -> SeriesT

Remove leading and trailing characters.

Parameters:

Name Type Description Default
characters str | None

The set of characters to be removed. All combinations of this set of characters will be stripped from the start and end of the string. If set to None (default), all leading and trailing whitespace is removed instead.

None

Returns:

Type Description
SeriesT

A new Series with leading and trailing characters removed.

Examples:

>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["apple", "\nmango"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.strip_chars().to_native()
shape: (2,)
Series: '' [str]
[
        "apple"
        "mango"
]

tail(n: int = 5) -> SeriesT

Take the last n elements of each string.

Parameters:

Name Type Description Default
n int

Number of elements to take. Negative indexing is supported (see note (1.))

5

Returns:

Type Description
SeriesT

A new Series containing the last n characters of each string.

Notes
  1. When the n input is negative, tail returns characters starting from the n-th from the beginning of the string. For example, if n = -3, then all characters except the first three are returned.
  2. If the length of the string has fewer than n characters, the full string is returned.

Examples:

>>> import pyarrow as pa
>>> import narwhals as nw
>>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.tail().to_native()
<pyarrow.lib.ChunkedArray object at ...>
[
  [
    "taata",
    "atata",
    "kkyun"
  ]
]

to_datetime(format: str | None = None) -> SeriesT

Parse Series with strings to a Series with Datetime dtype.

Notes
  • pandas defaults to nanosecond time unit, Polars to microsecond. Prior to pandas 2.0, nanoseconds were the only time unit supported in pandas, with no ability to set any other one. The ability to set the time unit in pandas, if the version permits, will arrive.
  • timezone-aware strings are all converted to and parsed as UTC.
Warning

As different backends auto-infer format in different ways, if format=None there is no guarantee that the result will be equal.

Parameters:

Name Type Description Default
format str | None

Format to use for conversion. If set to None (default), the format is inferred from the data.

None

Returns:

Type Description
SeriesT

A new Series with datetime dtype.

Examples:

>>> import polars as pl
>>> import narwhals as nw
>>> s_native = pl.Series(["2020-01-01", "2020-01-02"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.to_datetime(
...     format="%Y-%m-%d"
... ).to_native()
shape: (2,)
Series: '' [datetime[μs]]
[
        2020-01-01 00:00:00
        2020-01-02 00:00:00
]

to_lowercase() -> SeriesT

Transform string to lowercase variant.

Returns:

Type Description
SeriesT

A new Series with values converted to lowercase.

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["APPLE", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.to_lowercase().to_native()
0    apple
1     None
dtype: object

to_uppercase() -> SeriesT

Transform string to uppercase variant.

Returns:

Type Description
SeriesT

A new Series with values converted to uppercase.

Notes

The PyArrow backend will convert 'ß' to 'ẞ' instead of 'SS'. For more info see: https://github.com/apache/arrow/issues/34599 There may be other unicode-edge-case-related variations across implementations.

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["apple", None])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.to_uppercase().to_native()
0    APPLE
1     None
dtype: object