String Methods

Python · Data Cleaning

Theory

Text columns have a .str accessor that applies string operations to every value at once and skips NaN safely. Cleaning methods include str.strip() (remove spaces at both ends), str.lower(), str.upper(), str.title() and str.replace('-', ' '). Testing methods return booleans for filters: str.contains('pur'), str.startswith('R'), str.endswith('.in'); pass case=False to ignore case and na=False to treat missing as False.

str.len() gives lengths and str[:3] slices. str.split('@') returns lists, and .str[1] takes an element from each list, so df['email'].str.split('@').str[1] gives the domain; expand=True returns separate columns instead. str.extract(r'(\d+)') pulls a regex group into a new column, for example the number from 'Order-1023'. str.cat() or plain + joins strings. Chaining is common: df['name'].str.strip().str.title() turns ' asha ' into 'Asha'.

Why we use it

Free-text fields are messy: extra spaces, mixed case, codes buried inside longer strings. The .str methods clean and parse a whole column in one expression, so keys match and categories group correctly.

When to use it

Use .str methods for any per-value text work on a column, especially before joins and groupbys. For heavy pattern logic, use str.extract with a regex; avoid apply with Python string functions, which is slower and trips on NaN.

How it works

  1. Text column (Series of strings)
  2. Clean: str.strip(), str.lower() / title(), str.replace()
  3. Need part of the text? Yes: str.split(...).str[i] or str.extract(regex). No: Keep the whole value.
  4. Filtering by text? Yes: str.contains / startswith with na=False. No: Use the cleaned column.
  5. Clean, parsed text columns

Syntax

s.str.strip() / .lower() / .title() / .replace(a, b)
s.str.contains(pat, case=False, na=False)
s.str.split(sep, expand=False).str[i]
s.str.extract(r'(regex)')
s.str.len()

Example

df['name'] = df['name'].str.strip().str.title()
df['domain'] = df['email'].str.split('@').str[1]

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic