Skip to content

narwhals.Series.str

contains

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

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

ends_with(suffix: str) -> SeriesT

Check if string values end with a substring.

Parameters:

Name Type Description Default
suffix str

suffix substring

required

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

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
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

len_chars() -> SeriesT

Return the length of each string as the number of 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

replace(
    pattern: str,
    value: str | SeriesT,
    *,
    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 | SeriesT

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

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

replace_all(
    pattern: str,
    value: str | SeriesT,
    *,
    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 | SeriesT

String that will replace the matched substring.

required
literal bool

Treat pattern as a literal string.

False

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

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

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

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

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

starts_with(prefix: str) -> SeriesT

Check if string values start with a substring.

Parameters:

Name Type Description Default
prefix str

prefix substring

required

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

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

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

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
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_date

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

Convert to date dtype.

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

Examples:

>>> import pyarrow as pa
>>> import narwhals as nw
>>> s_native = pa.chunked_array([["2020-01-01", "2020-01-02"]])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.to_date(format="%Y-%m-%d").to_native()
<pyarrow.lib.ChunkedArray object at ...>
[
  [
    2020-01-01,
    2020-01-02
  ]
]

to_datetime

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

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

to_lowercase() -> SeriesT

Transform string to lowercase variant.

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

to_uppercase() -> SeriesT

Transform string to uppercase variant.

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

zfill

zfill(width: int) -> SeriesT

Pad strings with zeros on the left.

Parameters:

Name Type Description Default
width int

The target width of the string. If the string is shorter than this width, it will be padded with zeros on the left.

required

Examples:

>>> import pandas as pd
>>> import narwhals as nw
>>> s_native = pd.Series(["+1", "-23", "456", "123456"])
>>> s = nw.from_native(s_native, series_only=True)
>>> s.str.zfill(5).to_native()
0     +0001
1     -0023
2     00456
3    123456
dtype: object