Skip to content
C

Strings

Python's text type in depth — indexing and slicing, immutability, the full toolbox of string methods, searching and replacing, f-string formatting, escape and raw strings, and an introduction to regular expressions.


Text is everywhere in programming — names, messages, file paths, API responses. Python's string type (str) comes with a huge set of built-in tools for working with text, and this file covers all of them in depth.


1. What is a String?

What is it?

A string is a sequence of characters — letters, numbers, symbols, spaces — treated as text, always written inside quotes.

Definition: A string is an immutable sequence of characters used to represent text in Python.

Why do we use it?

Nearly every program deals with text in some form: usernames, messages, product names, error messages, file contents. Strings are how Python represents and manipulates all of that.

Creation

python
name = "Aditi" message = 'Hello there!' multiline = """This is a multi-line string"""

Both single '...' and double "..." quotes work identically — pick one style and stay consistent across your project.

Important Points

  • Strings are immutable — once created, a string's characters cannot be changed in place (any "modification" actually creates a new string).
  • Strings can use single, double, or triple quotes.

2. Indexing and Slicing

What is it?

Since a string is a sequence of characters, each character has a position (index), starting from 0.

Simple Example

python
word = "Python" print(word[0]) # P (first character) print(word[-1]) # n (last character) print(word[2:5]) # tho (slice from index 2 up to, but not including, 5) print(word[:3]) # Pyt (from the start up to index 3) print(word[3:]) # hon (from index 3 to the end) print(word[::-1]) # nohtyP (reversed string!)

Explanation of the Code

  • word[2:5] grabs characters at index 2, 3, and 4 — the slice stops before index 5.
  • word[::-1] uses a step of -1, which reverses the entire string — a very common trick for palindrome checks.

Common Mistakes

  • Trying to change a character directly: word[0] = "J"TypeError, because strings are immutable.
  • Forgetting slicing stops before the end index, not at it.

Important Points

  • Indexing starts at 0.
  • Negative indices count from the end (-1 is the last character).
  • string[::-1] is the standard trick to reverse a string.

Practice

  1. Given word = "Programming", print the first 4 characters and the last 4 characters.
  2. Reverse the string "Hello World" using slicing.

3. String Immutability

What is it?

Once a string is created, its individual characters cannot be changed. Any operation that seems to "modify" a string actually creates and returns a brand new string.

Simple Example

python
name = "aditi" name = name.capitalize() # this creates a NEW string, doesn't modify the original in place print(name) # Aditi

Important Points

  • If you need a "changeable" sequence of characters, convert to a list, modify it, then join it back into a string (list(word) ... "".join(...)).
  • Immutability makes strings safe to share and use as dictionary keys.

4. Common String Methods

What is it?

Python strings come with dozens of built-in methods for cleaning, transforming, and inspecting text.

Case Conversion

python
text = "Hello World" print(text.upper()) # HELLO WORLD print(text.lower()) # hello world print(text.title()) # Hello World print(text.capitalize()) # Hello world

Cleaning Whitespace

python
raw = " Hello World " print(raw.strip()) # "Hello World" (removes leading/trailing spaces) print(raw.lstrip()) # removes only leading spaces print(raw.rstrip()) # removes only trailing spaces

Splitting and Joining

python
sentence = "Python is fun" words = sentence.split() # ['Python', 'is', 'fun'] print(words) csv_line = "Aditi,21,CS" fields = csv_line.split(",") # ['Aditi', '21', 'CS'] print(fields) joined = " ".join(["Python", "is", "awesome"]) print(joined) # "Python is awesome"

Checking Content

python
print("hello123".isalpha()) # False (contains digits) print("hello".isalpha()) # True print("123".isdigit()) # True print("Hello".startswith("He")) # True print("Hello".endswith("lo")) # True

Table — Frequently Used String Methods

MethodPurpose
.upper() / .lower()Convert case
.strip()Remove leading/trailing whitespace
.split(sep)Break a string into a list
.join(list)Combine a list into a string
.replace(old, new)Replace occurrences of a substring
.find(sub)Find index of substring (returns -1 if not found)
.count(sub)Count occurrences of a substring
.startswith(sub) / .endswith(sub)Check start/end of string
.isalpha() / .isdigit() / .isalnum()Check character types

Common Mistakes

  • Forgetting that string methods return a new string — they don't change the original: text.upper() alone does nothing unless you store or print the result.
  • Using .split(",") on data that has extra spaces around commas, leading to fields like " Aditi" with a leading space.

Important Points

  • All string methods return new strings — none modify the string in place (because strings are immutable).
  • .split() with no argument splits on any whitespace and handles multiple spaces gracefully.

Practice

  1. Take a sentence and print how many words it contains using .split().
  2. Clean up the string " PYTHON is Fun " — strip whitespace and convert to title case.

5. Searching and Replacing

Searching

python
sentence = "Python is a powerful language" print(sentence.find("powerful")) # 12 (starting index) print(sentence.find("Java")) # -1 (not found) print("Python" in sentence) # True

Comparison Table — find() vs index()

find()index()
If not foundReturns -1Raises ValueError
Best whenSubstring might not existYou're sure the substring exists

Replacing

python
sentence = "I like Java" updated = sentence.replace("Java", "Python") print(updated) # I like Python

Real-World Example

Search-and-replace is used everywhere — cleaning messy user input, censoring words, or updating a template with real values.

Common Mistakes

  • Using .index() on a substring that might not exist, causing a crash — prefer .find() or check with in first.
  • Forgetting .replace() returns a new string; the original string is unchanged.

Practice

  1. Check if the word "Python" exists in a given sentence, and print its position if found.
  2. Replace all occurrences of "cat" with "dog" in a given sentence.

6. String Formatting

What is it?

String formatting means inserting variable values into a string in a clean, readable way — instead of manually concatenating pieces with +.

The Three Approaches

1. Old style (`%` formatting) — rarely used in modern code, but you may see it in older codebases:

python
name = "Aditi" print("Hello, %s!" % name)

2. `.format()` method:

python
name = "Aditi" age = 21 print("My name is {} and I am {} years old".format(name, age))

3. f-strings (modern, recommended) — Python 3.6+:

python
name = "Aditi" age = 21 print(f"My name is {name} and I am {age} years old")

Output (same for all three):

My name is Aditi and I am 21 years old

Why f-strings Are Preferred

python
price = 49.5 print(f"Price: ${price:.2f}") # Price: $49.50

Explanation: Inside an f-string, {price:.2f} formats the number to exactly 2 decimal places — very useful for money, percentages, and measurements.

Important Points

  • f-strings are the modern standard — cleaner, faster, and easier to read than .format() or %.
  • You can put any valid expression inside {} in an f-string, not just a variable: f"{2 + 2}" gives "4".

Practice

  1. Use an f-string to print a sentence combining your name and favorite number.
  2. Format the number 3.14159 to display only 2 decimal places using an f-string.

7. Escape Characters

What is it?

Escape characters let you include special characters (like a newline or a quote) inside a string using a backslash \.

Common Escape Characters

EscapeMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote

Simple Example

python
print("Line 1\nLine 2") print("Name:\tAditi") print("She said, \"Python is great!\"")

Output:

Line 1
Line 2
Name:	Aditi
She said, "Python is great!"

Common Mistakes

  • Forgetting to escape quotes when the same quote type is used inside the string: "She said, "hi""SyntaxError.

8. Raw Strings

What is it?

A raw string tells Python to treat backslashes as literal characters, not as the start of an escape sequence. Written by prefixing the string with r.

Simple Example

python
path = r"C:\Users\Aditi\Documents" print(path)

Output:

C:\Users\Aditi\Documents

Without the r prefix, \U and other sequences could be misinterpreted as escape characters, causing errors or unexpected output.

Real-World Example

Raw strings are especially useful for file paths (Windows uses backslashes) and regular expression patterns, which rely heavily on backslashes.

Important Points

  • Prefix a string with r to make it "raw" — Python ignores escape sequences inside it.
  • Very commonly used with the re module (regular expressions) and Windows file paths.

9. Multiline Strings

What is it?

Triple quotes ("""...""" or '''...''') let a string span multiple lines exactly as typed.

Simple Example

python
message = """Dear Student, Congratulations on completing this course! Best regards, Your Instructor""" print(message)

Important Points

  • Multiline strings preserve line breaks and spacing exactly as written.
  • Often used for docstrings (documentation inside functions/classes) as well as multi-line text output.

10. Introduction to Regular Expressions

What is it?

Regular expressions (regex) are patterns used to search, match, and validate text based on rules — like "does this look like a valid email address?" This is just an introduction; the full Regular Expressions file covers this in depth later in the course.

Simple Example

python
import re text = "Contact us at support@example.com" match = re.search(r"[\w.-]+@[\w.-]+", text) if match: print("Email found:", match.group())

Output:

Email found: support@example.com

Explanation

  • re.search() scans the text looking for a pattern.
  • The pattern [\w.-]+@[\w.-]+ roughly means "some letters/numbers/dots, then @, then more letters/numbers/dots" — a simplified email pattern.
  • .group() returns the actual matched text.

Important Points

  • The re module is Python's built-in tool for regular expressions.
  • Regex is extremely powerful for validating formats (emails, phone numbers, passwords) — covered fully later.

Common Beginner Mistakes — Summary for This Section

  • Trying to modify a string directly (word[0] = "x") — strings are immutable.
  • Forgetting string methods return new strings rather than modifying in place.
  • Confusing .find() (safe, returns -1) with .index() (raises an error if not found).
  • Forgetting the r prefix when working with file paths or regex patterns containing backslashes.

Cheat Sheet — Strings

python
s = "Hello World" s[0]; s[-1]; s[2:5]; s[::-1] # indexing & slicing s.upper(); s.lower(); s.title() # case conversion s.strip(); s.split(); "-".join([...]) # cleaning & splitting s.replace("old", "new") # replacing s.find("World"); "World" in s # searching f"{name} is {age} years old" # f-string formatting r"C:\Users\Name" # raw string """multi line""" # multiline string

Mini Project: Password Strength Checker

Objective

Build a program that checks whether a password is "Strong," "Medium," or "Weak" based on simple string rules.

Requirements

  • Password should be checked for: length, presence of digits, presence of uppercase letters, presence of special characters.
  • Classify strength based on how many rules are satisfied.

Concepts Used

Strings, string methods, if-elif-else, loops (to check characters).

Complete Code

python
password = input("Enter a password: ") length_ok = len(password) >= 8 has_digit = any(char.isdigit() for char in password) has_upper = any(char.isupper() for char in password) has_special = any(char in "!@#$%^&*" for char in password) score = sum([length_ok, has_digit, has_upper, has_special]) if score == 4: strength = "Strong" elif score >= 2: strength = "Medium" else: strength = "Weak" print(f"Password Strength: {strength}")

Code Explanation

  • any(char.isdigit() for char in password) checks if at least one character in the password is a digit, using a generator expression (a compact loop-like check).
  • score adds up how many of the four checks passed (True counts as 1, False as 0).
  • The final if-elif-else classifies the password based on the score.

Sample Output

Enter a password: Python@123
Password Strength: Strong

Possible Improvements

  • Give specific feedback on which rule failed (e.g., "Add at least one special character").
  • Reject common passwords like "password123" using a blocklist.

Challenge Task

Extend the checker to also reject passwords that contain the user's own name or username.


Interview Questions

Q1. Are strings mutable or immutable in Python? Answer: Immutable — once created, a string's characters cannot be changed. Any operation that appears to modify a string actually returns a new string.

Q2. What is the difference between `find()` and `index()`? Answer: find() returns -1 if the substring isn't found; index() raises a ValueError in that case.

Q3. What is an f-string, and why is it preferred? Answer: An f-string (formatted string literal, prefixed with f) lets you embed expressions directly inside {} within a string. It's preferred because it's more readable and generally faster than .format() or % formatting.

Q4. What does a raw string do? Answer: A raw string (prefixed with r) tells Python to treat backslashes as literal characters instead of escape sequence starters — useful for file paths and regex patterns.

Q5. How do you reverse a string in Python? Answer: Using slicing with a step of -1: string[::-1].


Practice Questions

Beginner

  1. Take a string and print it in uppercase and lowercase.
  2. Check if a given string starts with "Py" and ends with "on".
  3. Count how many vowels are in a given string.
  4. Reverse a given string using slicing.
  5. Replace all spaces in a sentence with underscores.

Intermediate

  1. Write a program to check if a given string is a palindrome (reads the same forwards and backwards).
  2. Count the number of words in a paragraph using .split().
  3. Write a program that capitalizes the first letter of every word in a sentence (without using .title()).
  4. Extract all digits from a string like "Room 42B, Floor 3".
  5. Write a program that checks whether a given password is at least 8 characters and contains at least one digit.

Challenge

  1. Write a program to check if two strings are anagrams of each other (contain the same letters, rearranged).
  2. Write a program to count the frequency of each character in a string using a dictionary.
  3. Write a simple text analyzer that reports word count, character count (excluding spaces), and the most frequently used word in a paragraph.

Mock Test

  • Strings - Quick Test

    10 questions covering indexing, slicing, immutability, string methods, formatting and raw strings.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems