Python Strings: Slicing, Methods and Escape Characters - Python with AI tutorial chapter 9
Python

Python Strings: Slicing, Methods and Escape Characters

Python with AI Tutorial · Chapter 9 of 48

Python strings are sequences of characters wrapped in single, double or triple quotes. You use them for names, invoice numbers, email addresses, file paths and every piece of text your program touches. In this chapter you will learn how to create Python strings, slice them, clean them with built-in methods and handle escape characters such as newlines and tabs.

Creating a string

Single and double quotes behave exactly the same, so pick one and stay consistent. Triple quotes let a string run over several lines, which is handy for addresses, SQL queries or email templates.

company = 'NeoTech Navigators'
tagline = "Learn Python with AI"
address = """12 Market Street
Pune, India"""

print(company)
print(tagline)
print(address)
Output:
NeoTech Navigators
Learn Python with AI
12 Market Street
Pune, India

Python does not have a separate character type. A single letter such as "A" is simply a string of length one.

Indexing and slicing

Every character has a position, counting from 0 at the front and from -1 at the back. A slice text[start:stop] returns the characters from start up to, but not including, stop. Leave either side empty to run to the edge, and add a third value for the step.

invoice = "INV-2026-00042"

print(invoice[0])        # first character
print(invoice[-1])       # last character
print(invoice[0:3])      # positions 0, 1 and 2
print(invoice[4:8])      # the year
print(invoice[-5:])      # last five characters
print(invoice[::-1])     # reversed
Output:
I
2
INV
2026
00042
24000-6202-VNI

Slicing never raises an error when the stop value runs past the end of the string; it simply returns what is available. Indexing a single position that does not exist, however, raises IndexError.

Length and membership

len() counts the characters, including spaces and punctuation. The in and not in keywords check whether one string appears inside another and return a boolean.

customer = "Acme Manufacturing Ltd"

print(len(customer))
print("Ltd" in customer)
print("GmbH" not in customer)
Output:
22
True
True

Python string methods

Methods are functions attached to the string, called with a dot. They never change the original string; each one returns a new string, so you must store or print the result. The table lists the ones you will reach for most often when cleaning business data.

Method What it does Example Result
upper() All characters to upper case "sku-9".upper() 'SKU-9'
lower() All characters to lower case "EMAIL".lower() 'email'
title() Capitalise each word "anita desai".title() 'Anita Desai'
strip() Remove spaces from both ends " hr ".strip() 'hr'
replace(a, b) Swap every a for b "1,250".replace(",", "") '1250'
split(sep) Break into a list "a,b,c".split(",") ['a', 'b', 'c']
join(list) Glue a list into one string "-".join(["2026", "09"]) '2026-09'
find(sub) Position of first match, or -1 "a@b.com".find("@") 1
count(sub) How many times it appears "banana".count("a") 3
startswith(s) True if it begins with s "INV-7".startswith("INV") True
endswith(s) True if it ends with s "report.xlsx".endswith(".xlsx") True
isdigit() True if all characters are digits "2026".isdigit() True

Here the methods clean a name that was typed with stray spaces and normalise an email address.

name = "  priya sharma  "
print(name.strip())
print(name.strip().title())

email = "Priya.Sharma@Example.com"
print(email.lower())
print(email.replace("Example.com", "neotech.com"))
print(email.startswith("Priya"))
print(email.find("@"))
Output:
priya sharma
Priya Sharma
priya.sharma@example.com
Priya.Sharma@neotech.com
True
12

Notice how name.strip().title() chains two methods. The first returns a new string and the second is called on that result, which keeps data-cleaning code short and readable.

Try it with AI

Ask your assistant to explain the difference between three similar-looking methods and to show you the output for each.

I am learning Python strings. Using the value "  Quarterly Sales Report  ", show me what strip(), lstrip() and rstrip() return, then show title(), capitalize() and swapcase() on the same value. Print each result inside square brackets so I can see the spaces.

Splitting and joining

split() turns one string into a list of pieces, which is the first step in reading a CSV line by hand. join() does the reverse and is called on the separator, not on the list.

csv_row = "Laptop,Electronics,899.00,3"
fields = csv_row.split(",")
print(fields)
print(fields[0], "costs", fields[2])

tags = ["excel", "python", "power-bi"]
print(" | ".join(tags))
Output:
['Laptop', 'Electronics', '899.00', '3']
Laptop costs 899.00
excel | python | power-bi

Called with no argument, split() breaks on any run of whitespace, so "a b\nc".split() gives ['a', 'b', 'c'].

Concatenation and repetition

The + operator joins strings and * repeats them. Both sides of + must be strings, so numbers need str() first, as covered in the casting chapter.

first = "Rahul"
last = "Verma"
full_name = first + " " + last
print(full_name)
print("-" * 20)
print("Total: " + str(1250))
Output:
Rahul Verma
--------------------
Total: 1250

For anything more than two or three pieces, the f-strings in the next chapter are cleaner and faster than a chain of plus signs.

Escape characters

A backslash tells Python that the next character has a special meaning. \n is a new line, \t is a tab, \" puts a quote inside a double-quoted string and \\ is a literal backslash. Prefix the string with r to make it a raw string in which backslashes are kept as typed, which is ideal for Windows paths and regular expressions.

print("Line one\nLine two")
print("Name:\tAmit")
print("She said \"approved\" yesterday")
print('It\'s ready')
print("C:\\Reports\\2026")
print(r"C:\Reports\2026")
Output:
Line one
Line two
Name:   Amit
She said "approved" yesterday
It's ready
C:\Reports\2026
C:\Reports\2026

Strings are immutable

Once created, a string cannot be changed in place. You cannot assign to text[0]; instead you build a new string and, if you like, store it back in the same variable.

code = "SKU-1001"
# code[0] = "s"   # TypeError: 'str' object does not support item assignment
code = code.lower()
print(code)
Output:
sku-1001
Common mistake: calling a method and forgetting to keep the result. name.strip() on its own line does nothing useful because the cleaned value is thrown away. Write name = name.strip() instead.
Try it with AI

Hand the assistant a messy real-world string and ask for a cleaning function, then ask it to explain each line.

Write a Python 3.12 function clean_customer(raw) that takes a string like "  mR. sanjay  KUMAR , DELHI " and returns "Sanjay Kumar (Delhi)". Use only string methods such as strip(), split(), title() and replace(); no regular expressions. Then explain what each method call does and show three test cases with their output.

Common mistakes

  • Mixing quote styles, such as 'Report", which raises SyntaxError. Open and close with the same quote.
  • Adding a number to a string with +. "Total: " + 1250 fails with TypeError; convert with str() or use an f-string.
  • Expecting split() to keep the separator. It removes it, so "a,b".split(",") has no commas left.
  • Assuming find() raises an error when nothing matches. It quietly returns -1, which is a valid index, so always test for it.
  • Forgetting that slicing stops one position before the stop value. text[0:3] returns three characters, not four.

Exercise

An HR export contains the line " emp-2041 | anita desai | finance ". Write code that prints the employee ID in upper case, the name in title case and the department with only the first letter capitalised, each on its own line.

Show answer
record = "  emp-2041 | anita desai | finance  "
parts = record.strip().split(" | ")

emp_id = parts[0].upper()
name = parts[1].title()
dept = parts[2].capitalize()

print(emp_id)
print(name)
print(dept)
Output:
EMP-2041
Anita Desai
Finance

strip() removes the outer spaces first so the split produces exactly three clean pieces.

Related chapters

FAQ

Are Python strings mutable?

No. A string cannot be changed after it is created. Methods such as upper() or replace() return a brand-new string, so assign the result to a variable if you want to keep it.

What is the difference between find() and index()?

Both return the position of the first match. find() returns -1 when the substring is missing, while index() raises a ValueError, which is useful when a missing value should stop the program.

How do I reverse a string in Python?

Use slicing with a negative step: text[::-1]. It returns a new string with the characters in reverse order and works on any string, including ones with spaces and symbols.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 9 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com