Python Strings: Complete Guide to Slicing, Formatting & String Methods

In Python, a string (str) is an immutable sequence of Unicode characters. Strings are among the most heavily used data structures in computer science, powering text processing, file parsing, web development, and database queries. In this lesson, you will master string indexing, the powerful slicing syntax, modern f-string formatting, and the most essential string manipulation methods.


1. String Indexing: Positive & Negative Indices

Every character in a Python string is assigned a positional index number. Python supports both positive indexing (starting from 0 on the left) and negative indexing (starting from -1 on the right):

# String indexing demonstration
word = "PYTHON"

# Positive:  P(0)  Y(1)  T(2)  H(3)  O(4)  N(5)
# Negative: P(-6) Y(-5) T(-4) H(-3) O(-2) N(-1)

print(word[0])   # 'P'
print(word[3])   # 'H'
print(word[-1])  # 'N' (Last character)
print(word[-2])  # 'O'

2. String Slicing: [start : stop : step]

Slicing allows extracting a substring sequence. The syntax follows three parameters:

• start: The index where extraction begins (inclusive). Defaults to 0.

• stop: The index where extraction ends (exclusive). Defaults to end of string.

• step: The stride or step value between characters. Defaults to 1.

text = "Veewom Programming Tutorial"

print(text[0:6])       # 'Veewom' (Characters from index 0 to 5)
print(text[7:18])      # 'Programming'
print(text[:6])        # 'Veewom' (Omitted start defaults to 0)
print(text[19:])       # 'Tutorial' (Omitted stop defaults to end)
print(text[::2])       # 'VewmPormigTtria' (Every 2nd character)

# THE FAMOUS REVERSE SLICE (Essential for BCA practicals!):
reversed_text = text[::-1]
print("Reversed:", reversed_text)

3. Modern String Formatting: F-Strings (PEP 498)

Formatted string literals (f-strings) provide the fastest, cleanest, and most readable way to format text in Python 3:

student = "Deepak Verma"
roll_no = 1042
cgpa = 9.4582

# Basic embedding:
print(f"Student: {student} (Roll: {roll_no})")

# Precision formatting (2 decimal places):
print(f"CGPA: {cgpa:.2f}")  # 9.46

# Expressions inside f-strings:
print(f"Uppercase: {student.upper()}, Passing Year: {2024 + 1}")

4. Top 15 Built-in String Methods

Method Description Example Code & Output
s.strip()Removes leading and trailing whitespace." hello ".strip() -> "hello"
s.lower() / upper()Converts string to lowercase / uppercase."Py".upper() -> "PY"
s.split(sep)Splits string into a list of substrings."a,b,c".split(",") -> ['a', 'b', 'c']
sep.join(list)Joins elements of an iterable into one string."-".join(['2024', '11', '04']) -> "2024-11-04"
s.replace(old, new)Replaces occurrences of substring."bad code".replace("bad", "good")
s.find(sub)Returns lowest index of sub (or -1 if missing)."python".find("th") -> 2
s.startswith(prefix)Returns True if string starts with prefix."https://veewom.com".startswith("https")
s.count(sub)Counts non-overlapping occurrences."banana".count("an") -> 2

Hands-on Practice: Palindrome Checker

Challenge: Write a program to check whether a given word is a Palindrome (reads the same forwards and backwards, ignoring case and spaces):

def is_palindrome(sentence: str) -> bool:
    # Clean text: remove spaces and convert to lowercase
    cleaned = "".join(sentence.lower().split())
    return cleaned == cleaned[::-1]

print(is_palindrome("Radar"))            # True
print(is_palindrome("Nurses Run"))        # True
print(is_palindrome("Python Tutorial"))  # False

Frequently Asked Questions (FAQ)

Can I change a single character in a string using indexing (e.g. s[0] = 'H')?

No! Strings are immutable. Attempting s[0] = 'H' raises a TypeError: 'str' object does not support item assignment. You must create a new string using slicing or s.replace().

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

Both search for a substring. However, if the substring is not found, find() returns -1, whereas index() raises a ValueError: substring not found.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!