w3resource

Pandas Series: str.strip() function

Series-str.strip() function

The str.strip() function is used to remove leading and trailing characters.
Strip whitespaces (including newlines) or a set of specified characters from each string in the Series/Index from left and right sides. Equivalent to str.strip().

Syntax:

Series.str.strip(self, to_strip=None)
Pandas Series: str.strip() function

Parameters:

Name Description Type/Default Value Required / Optional
to_strip Specifying the set of characters to be removed. All combinations of this set of characters will be stripped. If None then whitespaces are removed. str or None, default None Required

Returns: Series/Index of objects

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(['1. Bat.  ', '2. Dog!\n', '3. fox?\t', np.nan])
s

Output:

0    1. Bat.  
1    2. Dog!\n
2    3. fox?\t
3          NaN
dtype: object

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(['1. Bat.  ', '2. Dog!\n', '3. fox?\t', np.nan])
s.str.strip()

Output:

0    1. Bat.
1    2. Dog!
2    3. fox?
3        NaN
dtype: object
Pandas Series: str.strip() function

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(['1. Bat.  ', '2. Dog!\n', '3. fox?\t', np.nan])
s.str.strip('123.!? \n\t')

Output:

0    Bat
1    Dog
2    fox
3    NaN
dtype: object

Previous: Series-str.startswith() function
Next: Series-str.swapcase() function



Follow us on Facebook and Twitter for latest update.