TutorialsPythonString Operations in Python

String Operations in Python

Slice, split, replace, strip and format text data — essential for cleaning messy datasets

String operations are one of the most-used Python skills in data cleaning. Real-world datasets have inconsistent text: extra spaces, mixed case, concatenated fields (like "FirstName LastName" in one column), date strings in wrong formats. Python strings give you 30+ built-in methods to fix all of these. In data analysis, you will use strings constantly: cleaning city names, extracting product codes, parsing dates, and building output messages.

Examples

Most-used string methods for data cleaning
text = "  Delhi NCR  "

# Cleaning
text.strip()          # "Delhi NCR"  — remove leading/trailing spaces
text.lower()          # "  delhi ncr  "
text.upper()          # "  DELHI NCR  "
text.title()          # "  Delhi Ncr  "

# Checking
"Delhi" in text       # True
text.startswith(" ")  # True
text.endswith("  ")   # True

# Replacing
text.replace("Delhi", "Mumbai")  # "  Mumbai NCR  "

# Splitting
"Sector 51, Noida".split(", ")   # ['Sector 51', 'Noida']
"2026-08-15".split("-")          # ['2026', '08', '15']

# Slicing (like Excel MID/LEFT/RIGHT)
code = "PROD-2026-001"
code[0:4]    # "PROD"  (LEFT 4)
code[-3:]    # "001"   (RIGHT 3)
code[5:9]    # "2026"  (MID from pos 5, length 4)
💡 String methods return a new string — they do not modify the original. Always assign the result: name = name.strip()
f-strings — format output cleanly
name = "Rahul"
sales = 450000
margin = 0.224

# f-string formatting
print(f"Analyst: {name}")
print(f"Sales: ₹{sales:,}")          # ₹4,50,000  (comma separator)
print(f"Margin: {margin:.1%}")        # 22.4%      (percentage)
print(f"Sales: ₹{sales/100000:.1f}L")# ₹4.5L      (in lakhs)

# Multi-line f-string
report = f"""
Sales Report
Analyst  : {name}
Revenue  : ₹{sales:,}
Margin   : {margin:.1%}
"""
print(report)

Key Points

  • strip() removes whitespace — always use it when reading text input
  • lower() before comparing strings: "Delhi" == "delhi" is False without it
  • split() is your best friend for parsing structured text data
  • String slicing uses [start:end] — end index is exclusive
  • f-strings (Python 3.6+) are cleaner than .format() or % formatting

Practice Question

A column has values like " Mumbai " with extra spaces. Which method removes leading and trailing spaces?

Related Topics

Python ListsStore, access and manipulate collections of data with Python listsData Cleaning with PandasRename columns, fix data types, remove duplicates, and standardise messy real-world dataString and Date Operations in PandasClean text columns and extract date parts with Pandas str and dt accessors