Skip to content

narwhals.Series.str

contains(pattern, *, literal=False)

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 pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> pets = ["cat", "dog", "rabbit and parrot", "dove", None]
>>> s_pd = pd.Series(pets)
>>> s_pl = pl.Series(pets)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.contains("parrot|dove").to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0    False
1    False
2     True
3     True
4     None
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (5,)
Series: '' [bool]
[
   false
   false
   true
   true
   null
]

ends_with(suffix)

Check if string values end with a substring.

Parameters:

Name Type Description Default
suffix str

suffix substring

required

Examples:

>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["apple", "mango", None]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.ends_with("ngo").to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0    False
1     True
2     None
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (3,)
Series: '' [bool]
[
   false
   true
   null
]

head(n=5)

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 pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> lyrics = ["Atatata", "taata", "taatatata", "zukkyun"]
>>> s_pd = pd.Series(lyrics)
>>> s_pl = pl.Series(lyrics)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.head().to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0    Atata
1    taata
2    taata
3    zukky
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (4,)
Series: '' [str]
[
   "Atata"
   "taata"
   "taata"
   "zukky"
]

len_chars()

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

Examples:

>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["foo", "Café", "345", "東京", None]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.len_chars().to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0    3.0
1    4.0
2    3.0
3    2.0
4    NaN
dtype: float64
>>> my_library_agnostic_function(s_pl)
shape: (5,)
Series: '' [u32]
[
   3
   4
   3
   2
   null
]

replace(pattern, value, *, literal=False, n=1)

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

Examples:

>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["123abc", "abc abc123"]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     s = s.str.replace("abc", "")
...     return s.to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0        123
1     abc123
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (2,)
Series: '' [str]
[
    "123"
    " abc123"
]

replace_all(pattern, value, *, literal=False)

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

Examples:

>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["123abc", "abc abc123"]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     s = s.str.replace_all("abc", "")
...     return s.to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0     123
1     123
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (2,)
Series: '' [str]
[
    "123"
    " 123"
]

slice(offset, length=None)

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 polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["pear", None, "papaya", "dragonfruit"]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.slice(4, length=3).to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0
1    None
2      ya
3     onf
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (4,)
Series: '' [str]
[
   ""
   null
   "ya"
   "onf"
]

Using negative indexes:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.slice(-3).to_native()
>>> my_library_agnostic_function(s_pd)
0     ear
1    None
2     aya
3     uit
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (4,)
Series: '' [str]
[
    "ear"
    null
    "aya"
    "uit"
]

starts_with(prefix)

Check if string values start with a substring.

Parameters:

Name Type Description Default
prefix str

prefix substring

required

Examples:

>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["apple", "mango", None]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.starts_with("app").to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0     True
1    False
2     None
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (3,)
Series: '' [bool]
[
   true
   false
   null
]

strip_chars(characters=None)

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 pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["apple", "\nmango"]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     s = s.str.strip_chars()
...     return s.to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0    apple
1    mango
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (2,)
Series: '' [str]
[
    "apple"
    "mango"
]

tail(n=5)

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 pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> lyrics = ["Atatata", "taata", "taatatata", "zukkyun"]
>>> s_pd = pd.Series(lyrics)
>>> s_pl = pl.Series(lyrics)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.tail().to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(s_pd)
0    atata
1    taata
2    atata
3    kkyun
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (4,)
Series: '' [str]
[
   "atata"
   "taata"
   "atata"
   "kkyun"
]

to_datetime(format=None)

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.

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 pandas as pd
>>> import polars as pl
>>> import pyarrow as pa
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["2020-01-01", "2020-01-02"]
>>> s_pd = pd.Series(data)
>>> s_pl = pl.Series(data)
>>> s_pa = pa.chunked_array([data])

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
...     s = nw.from_native(s_native, series_only=True)
...     return s.str.to_datetime(format="%Y-%m-%d").to_native()

We can then pass any supported library such as pandas, Polars, or PyArrow::

>>> my_library_agnostic_function(s_pd)
0   2020-01-01
1   2020-01-02
dtype: datetime64[ns]
>>> my_library_agnostic_function(s_pl)
shape: (2,)
Series: '' [datetime[μs]]
[
   2020-01-01 00:00:00
   2020-01-02 00:00:00
]
>>> my_library_agnostic_function(s_pa)
<pyarrow.lib.ChunkedArray object at 0x...>
[
  [
    2020-01-01 00:00:00.000000,
    2020-01-02 00:00:00.000000
  ]
]

to_lowercase()

Transform string to lowercase variant.

Examples:

>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT, IntoFrameT
>>> data = {"fruits": ["APPLE", "MANGO", None]}
>>> df_pd = pd.DataFrame(data)
>>> df_pl = pl.DataFrame(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(df_native: IntoFrameT) -> IntoFrameT:
...     df = nw.from_native(df_native)
...     return df.with_columns(
...         lower_col=nw.col("fruits").str.to_lowercase()
...     ).to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(df_pd)
  fruits lower_col
0  APPLE     apple
1  MANGO     mango
2   None      None
>>> my_library_agnostic_function(df_pl)
shape: (3, 2)
┌────────┬───────────┐
│ fruits ┆ lower_col │
│ ---    ┆ ---       │
│ str    ┆ str       │
╞════════╪═══════════╡
│ APPLE  ┆ apple     │
│ MANGO  ┆ mango     │
│ null   ┆ null      │
└────────┴───────────┘

to_uppercase()

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 polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoFrameT
>>> data = {"fruits": ["apple", "mango", None]}
>>> df_pd = pd.DataFrame(data)
>>> df_pl = pl.DataFrame(data)

We define a dataframe-agnostic function:

>>> def my_library_agnostic_function(df_native: IntoFrameT) -> IntoFrameT:
...     df = nw.from_native(df_native)
...     return df.with_columns(
...         upper_col=nw.col("fruits").str.to_uppercase()
...     ).to_native()

We can then pass either pandas or Polars to func:

>>> my_library_agnostic_function(df_pd)
 fruits  upper_col
0  apple      APPLE
1  mango      MANGO
2   None       None
>>> my_library_agnostic_function(df_pl)
shape: (3, 2)
┌────────┬───────────┐
│ fruits ┆ upper_col │
│ ---    ┆ ---       │
│ str    ┆ str       │
╞════════╪═══════════╡
│ apple  ┆ APPLE     │
│ mango  ┆ MANGO     │
│ null   ┆ null      │
└────────┴───────────┘