Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 04

Python Strings

4 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A string is an ordered, immutable sequence of characters used to store text.

This chapter covers creating strings, the most useful string methods, formatting with f-strings and slicing and indexing.

Text processing is in almost every program: names, messages, files, logs, URLs and JSON.

Cleaning input, building reports, parsing log files, generating messages and web scraping.

1

Python Strings

A string (str) is an ordered, immutable sequence of Unicode characters. It is created by placing text inside single quotes, double quotes or triple quotes.

In short: A string is text. You can read its characters one by one but you cannot change them in place.

String as indexed characters

Think about it

Almost all user-facing data is text. Understanding immutability avoids silent bugs. A chat app stores messages as strings, trims them, checks length and shows them.

Create: 'a', "b", and multi-line """text""".

Escape sequences: \n new line, \t tab, \\ backslash, \' and \" quotes.

Raw strings r"C:\new" keep backslashes.

Operations: + joins, * repeats, in tests membership, len() counts characters, == and < compare using Unicode order.

Iteration: for ch in text gives each character.

Immutability: s[0] = "X" raises TypeError; every change creates a NEW string, so s = s.

upper() must be re-assigned.

Joining many strings in a loop with + is slow; collect them in a list and use "".

join().

Strings are Unicode, so "नमस्ते" and emoji work.

Convert: str(123), int("123").

Encoding: "hi".

encode("utf-8") gives bytes.

Strings are hashable and can be dictionary keys.

Key points

  • Escape sequence: Backslash code like \n that stands for a special character.
  • Immutable: Cannot be changed after creation.
  • Unicode: Standard that gives every character a number.
  • Raw string: r"..." string that does not process backslashes.
  • Triple quotes: """ or ''' allow multi-line strings.
  • Strings are immutable; methods return new strings.
  • Use "".join(list) to join many strings efficiently.
  • len("abc") is 3; indexes start at 0.
  • Single and double quotes behave the same.

Example

Code
creating and using strings:
a = 'single'
b = "double"
c = """multi
line"""
print(a, b)
print(c)

print("Hi " + "there", "ab" * 3)       # Hi there ababab
print(len("python"), "th" in "python") # 6 True
print("a\tb\nc")                       # tab and new line
print(r"C:\new\table")                 # raw string
print("It's", 'say "hi"')

s = "hello"
# s[0] = "H"          # TypeError
s = "H" + s[1:]       # build a new string
print(s)              # Hello

for ch in "abc":
    print(ch, end=" ")                 # a b c
print()
print(", ".join(["red", "green", "blue"]))   # red, green, blue
print("apple" < "banana")              # True
2

Python String Methods

String methods are built-in functions attached to str objects that clean, search, change and test text. They never modify the original string; they return a new value.

In short: Methods are ready-made tools like upper(), strip(), split() and replace().

Think about it

Real input is messy: extra spaces, wrong case and separators. Methods clean it in one line. A signup form trims the email, lowercases it and checks that it contains "@".

Case: upper(), lower(), title(), capitalize(), swapcase(), casefold().

Clean: strip(), lstrip(), rstrip() remove spaces or given characters from the ends.

Search: find(x) returns the index or -1; index(x) raises ValueError if missing; count(x); startswith(); endswith(); rfind().

Change: replace(old, new, count); center(w), ljust(w), rjust(w), zfill(w).

Split/join: split(sep, maxsplit) returns a list; splitlines(); partition(sep) returns a 3-tuple; "sep".

join(iterable).

Test: isalpha(), isdigit(), isalnum(), isspace(), isupper(), islower(), isnumeric().

Translate: str.

maketrans() and translate().

Method chaining works: text.

strip().

lower().

split().

Because strings are immutable, always capture the result: text = text.

strip().

Key points

  • Method: Function that belongs to an object, called with a dot.
  • strip(): Removes whitespace (or chosen characters) from both ends.
  • split(): Breaks a string into a list of parts.
  • join(): Combines list items into one string using a separator.
  • find(): Returns index of a substring or -1.
  • Methods return new strings; the original stays unchanged.
  • find() returns -1 if missing; index() raises ValueError.
  • split() with no argument splits on any whitespace and drops empties.
  • join() is called on the separator: ",".join(items).

Example

Code
the most used string methods:
s = "  Hello, World  "
print(s.strip())                  # 'Hello, World'
print(s.lower(), s.upper())
print("hello world".title())       # Hello World
print("python".capitalize())       # Python

t = "banana"
print(t.find("an"), t.find("z"))   # 1 -1
print(t.count("a"))                # 3
print(t.replace("a", "o", 2))      # bonona
print(t.startswith("ba"), t.endswith("na"))   # True True

print("a,b,,c".split(","))         # ['a', 'b', '', 'c']
print("a  b   c".split())          # ['a', 'b', 'c']
print("-".join("abc"))             # a-b-c
print("key=value".partition("="))  # ('key', '=', 'value')

print("42".isdigit(), "4a".isalnum(), "ab".isalpha())  # True True True
print("7".zfill(3), "hi".center(6, "*"))               # 007 **hi**

# chaining and re-assigning
email = "  USER@Mail.COM "
email = email.strip().lower()
print(email)                       # user@mail.com

# index() raises, find() does not
try:
    "abc".index("z")
except ValueError:
    print("not found")
3

String Formatting & f-strings

String formatting inserts values into text. Python supports f-strings (formatted string literals, Python 3.6+), the str.format() method and the older % operator. An f-string starts with f and evaluates expressions inside { } at run time.

In short: Put f before the quotes and write variables inside curly braces. Python fills them in.

Think about it

Reports, logs, receipts and messages need aligned, rounded and readable output. An invoice prints items with prices rounded to two decimals and right-aligned.

f-string: f"Name: {name}, Age: {age}".

Any expression works: f"{a + b}", f"{name.

upper()}".

Format spec after a colon: {x:.

2f} two decimals, {n:,} thousands separator, {n:08.3f} zero padded, {s:>10} right align, {s:<10} left, {s:^10} centre, {p:.

1%} percent, {n:b} binary, {n:x} hex, {n:e} scientific.

Debug form: f"{x=}" prints x=value (3.8+).

Use !

r for repr: f"{s!

r}".

Literal braces: {{ and }}.

str.

format(): "{} is {}".

format("a", 1), with positions {0} or names {name}.

Old style: "%s is %d" % ("a", 1), "%.

2f" % 3.14159.

Prefer f-strings: they are the clearest and fastest.

Before Python 3.12 do not reuse the same quote type inside the braces.

Use format() when the template is stored separately from the data.

Key points

  • f-string: String prefixed with f that evaluates { } expressions.
  • Format spec: Code after : that controls width, precision and type.
  • Placeholder: Position in a template where a value is inserted.
  • repr(): Developer-friendly text form of an object (!r in f-strings).
  • f-strings need Python 3.6 or later.
  • {value:.2f} rounds to 2 decimals.
  • Use {{ and }} to print literal braces.
  • {x=} is a quick debug print.

Example

Code
f-strings, format() and %:
name, age, pi = "Asha", 21, 3.14159
print(f"Name: {name}, Age: {age}")            # Name: Asha, Age: 21
print(f"Next year: {age + 1}")                # Next year: 22
print(f"Upper: {name.upper()}")               # Upper: ASHA

print(f"{pi:.2f}")                            # 3.14
print(f"{1234567:,}")                         # 1,234,567
print(f"{42:08.3f}")                          # 0042.000
print(f"[{'hi':>6}] [{'hi':<6}] [{'hi':^6}]") # [    hi] [hi    ] [  hi  ]
print(f"{0.256:.1%}")                         # 25.6%
print(f"{255:b} {255:x} {255:o}")             # 11111111 ff 377
print(f"{{braces}} {name!r}")                 # {braces} 'Asha'

x = 3.8
print(f"{x=}")                                # x=3.8

# older styles
print("{} scored {}".format("Ravi", 90))            # Ravi scored 90
print("{1} {0}".format("world", "hello"))           # hello world
print("{n} is {a}".format(n="Sam", a=20))
print("%s has %d items costing %.2f" % ("cart", 3, 9.5))

# table
for item, price in [("Pen", 5.5), ("Notebook", 42)]:
    print(f"{item:<10}{price:>8.2f}")
4

String Slicing & Indexing

Indexing picks one character using its position: s[i]. Slicing picks a part of a string using s[start:stop:step]. Indexes start at 0 from the left and at -1 from the right. The stop index is not included.

In short: Indexing takes one letter. Slicing takes a piece. Negative numbers count from the end.

Think about it

Slicing extracts parts of text without loops, and is used in countless interview questions. Taking the last 4 digits of a card number to display "XXXX-1234".

For s = "Python": positions 0..

5 on the left and -6..

-1 on the right.

s[0] is "P", s[-1] is "n".

Slice s[a:b] gives characters from a up to b-1.

Omitted start means the beginning; omitted stop means the end; s[:] copies the whole string.

Step

  • 1s[::2] takes every second character
  • 2s[::-1] reverses the string

With a negative step, start and stop go right to left.

Out-of-range slices are safe (s[2:100] works) but out-of-range indexes raise IndexError.

Slices always return a new string.

The same rules work for lists and tuples.

Useful patterns: s[:n] first n characters, s[-n:] last n characters, s[::-1] == s checks a palindrome, s[1:-1] removes first and last character.

A slice object slice(a, b, c) can be stored and reused.

Key points

  • Index: Position number of an item, starting at 0.
  • Negative index: Position counted from the end; -1 is the last.
  • Slice: Part of a sequence produced by [start:stop:step].
  • Stop (exclusive): The character at stop is not included.
  • IndexError: Error raised when an index is outside the string.
  • s[a:b] excludes index b.
  • s[::-1] reverses a string.
  • s[10] on a short string raises IndexError; s[10:] returns "".
  • Slicing never changes the original string.

Example

Code
indexing, slicing and palindrome:
s = "Python"
#    P  y  t  h  o  n
#    0  1  2  3  4  5
#   -6 -5 -4 -3 -2 -1
print(s[0], s[-1], s[2])      # P n t
print(s[1:4])                 # yth
print(s[:2], s[2:])           # Py thon
print(s[-3:])                 # hon
print(s[::2])                 # Pto
print(s[::-1])                # nohtyP
print(s[1:-1])                # ytho
print(s[4:1:-1])              # oht
print(s[:])                   # Python

print(s[2:100])               # thon (slice is safe)
try:
    print(s[10])
except IndexError as e:
    print("IndexError:", e)

def is_palindrome(t):
    t = t.lower()
    return t == t[::-1]
print(is_palindrome("Level"), is_palindrome("Python"))   # True False

card = "1234567812345678"
print("XXXX-XXXX-XXXX-" + card[-4:])   # XXXX-XXXX-XXXX-5678

Solved examples

Example 01 · Basic

Reverse the string "Python" and print the first three letters of the result.

Given Data:
    Required To Find:

    nohtyP and noh

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: rev = s[::-1] gives "nohtyP"
    Step 2: rev[:3] gives "noh"
    Final Answer: s = "Python" rev = s[::-1] print(rev, rev[:3]) # nohtyP noh

    Approach note: A negative step reads the string from right to left.

    Example 02 · Intermediate

    Count the vowels in the sentence "Education is power".

    Given Data:
      Required To Find:

      Number of vowels

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Lowercase the text
      Step 2: Loop through each character
      Step 3: Count characters that are in "aeiou"
      Final Answer: text = "Education is power" count = 0 for ch in text.lower(): if ch in "aeiou": count += 1 print(count) # 8

      Approach note: One-liner: sum(ch in "aeiou" for ch in text.lower()).

      Example 03 · Intermediate

      Print a receipt line for item "Pen" with price 5.5 and quantity 3 using an f-string with 2 decimals.

      Given Data:
        Required To Find:

        Pen x 3 = 16.50

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Compute total = 5.5 * 3 = 16.5
        Step 2: Use {total:.2f} to keep two decimals
        Final Answer: item, price, qty = "Pen", 5.5, 3 print(f"{item} x {qty} = {price * qty:.2f}") # Pen x 3 = 16.50

        Approach note: Any expression can sit inside the braces.

        Example 04 · Basic

        From s = "doubtclip", print characters from index 2 to 6 (exclusive of 7) and the length of s.

        Given Data:
          Required To Find:

          Slice and length

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: s[2:7] takes indexes 2,3,4,5,6
          Step 2: That substring is "ubtcl"
          Step 3: len(s) is 9
          Final Answer: print(s[2:7], len(s)) # ubtcl 9

          Approach note: Stop index is exclusive; length is counted separately with len().

          Real-world applications

          Python

          Using Python Strings in real projects

          Cleaning input, building reports, parsing log files, generating messages and web scraping.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: s[0] = "X" changes the first letter.

          Why this is wrong: Strings are immutable.

          ✅ Verified Truth: Build a new string: "X" + s[1:].

          ⚠️ Exam Tip: Common TypeError question.

          ❌ Myth: s.upper() changes s.

          Why this is wrong: Methods return a new string.

          ✅ Verified Truth: Use s = s.upper() to keep the change.

          ⚠️ Exam Tip: Always assign the result.

          ❌ Myth: s[1:4] includes index 4.

          Why this is wrong: The stop index is exclusive.

          ✅ Verified Truth: s[1:4] gives indexes 1, 2 and 3.

          ⚠️ Exam Tip: Length of s[a:b] is b - a.

          ❌ Myth: find() and index() are identical.

          Why this is wrong: find returns -1 when missing; index raises ValueError.

          ✅ Verified Truth: Choose by how you want to handle absence.

          ⚠️ Exam Tip: Mention both behaviours.

          Revision notes

          A string is an ordered, immutable sequence of characters used to store text. This chapter covers creating strings, the most useful string methods, formatting with f-strings and slicing and indexing.

          High-Yield Quick Revision Points

          1. str is an ordered, immutable sequence of Unicode characters.
          2. Quotes: single, double, triple for multi-line; r"" for raw; \n \t escapes.
          3. Methods return new strings: upper, lower, strip, replace, split, join, find, count, startswith.
          4. find() gives -1 if missing; index() raises ValueError.
          5. f"{value:.2f}" rounds; {n:,} adds commas; {x:>8} aligns; {x=} debugs.
          6. Indexing starts at 0; negative index starts at -1 from the end.
          7. s[start:stop:step]; stop is excluded; s[::-1] reverses; slices never raise IndexError.
          8. Use "".join(list) instead of += in loops for speed.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          What is the output of "Python"[::-1]?

          Question 2 · MCQ (Interview / semester)

          What does "hello".find("z") return?

          Question 3 · MCQ (Interview / semester)

          What is f"{3.14159:.2f}"?

          Question 4 · MCQ (Interview / semester)

          Which statement raises an error?

          Question 5 · MCQ (Interview / semester)

          What is "a-b-c".split("-")?

          Question 6 · MCQ (Interview / semester)

          What is "Python"[1:4]?

          Question 7 · MCQ (Interview / semester)

          Which method joins list items into one string?