SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 03
← Back to Course Index

Strings


On This Page

Module 3: Strings


3.1  String Creation

A string is a sequence of characters enclosed in quotes. Python allows single, double, and triple quotes — all work the same way, giving you flexibility when text itself contains quotes.

► Creating Strings
s1 = 'Samantus'
s2 = "Web Training Institute"
s3 = """This is a
multi-line string"""

print(s1, s2)
print(s3)
✓ Tip
Use double quotes when your text contains an apostrophe, e.g. "It's a great course" — this avoids confusing Python by ending the string early.

3.2  Indexing

Every character in a string has a position number called an index. Python indexing starts at 0, and negative indexes count from the end of the string.

► Accessing Characters by Index
course = "PYTHON"
print(course[0])   # first character
print(course[5])   # last character
print(course[-1])  # last character (negative index)
print(course[-6])  # first character (negative index)
Output
P
N
N
P
✗ Common Mistake
Trying to access an index that doesn't exist (e.g. course[10] on a 6-letter word) causes an "IndexError: string index out of range" — always check the string length first with len().

3.3  Slicing

Slicing lets you extract a portion (substring) of a string using the format string[start:stop:step]. The stop index is never included.

► Slicing Examples
text = "Samantus Web Training"
print(text[0:8])     # Samantus
print(text[9:12])    # Web
print(text[:8])      # from start to index 8
print(text[9:])      # from index 9 to end
print(text[::-1])    # reversed string
Output
Samantus
Web
Samantus
Web Training
gniniarT beW sutnamaS

3.4  Escape Characters

Escape characters let you include special characters (like quotes or new lines) inside a string using a backslash \.

Escape SequenceMeaning
\nNew line
\tTab space
\\Backslash itself
\'Single quote inside a single-quoted string
\"Double quote inside a double-quoted string
► Using Escape Characters
print("Samantus\nWeb Training Institute")
print("Course:\tPython for Data Analytics")
print('It\'s a great course')
Output
Samantus
Web Training Institute
Course:    Python for Data Analytics
It's a great course

3.5  String Formatting

String formatting lets you insert variable values neatly into text. The modern, recommended way is using f-strings (formatted string literals).

► Three Ways to Format Strings
name = "Priya"
fee = 15000

# 1. f-string (recommended)
print(f"{name} paid Rs.{fee}")

# 2. .format() method
print("{} paid Rs.{}".format(name, fee))

# 3. % operator (older style)
print("%s paid Rs.%d" % (name, fee))
Output
Priya paid Rs.15000
Priya paid Rs.15000
Priya paid Rs.15000
✓ Instructor Tip
Teach f-strings as the primary method — they are the modern industry standard and are easier to read than the older .format() or % styles.

3.6  Important String Methods

Python strings come with many built-in methods for cleaning, searching, and transforming text.

MethodPurposeExample
upper()Converts to uppercase"data".upper() → "DATA"
lower()Converts to lowercase"DATA".lower() → "data"
strip()Removes leading/trailing spaces" hi ".strip() → "hi"
replace()Replaces text"cat".replace("c","b") → "bat"
split()Splits into a list"a,b,c".split(",") → [a,b,c]
join()Joins a list into a string",".join(["a","b"]) → "a,b"
find()Finds index of substring"hello".find("l") → 2
len()Returns string lengthlen("data") → 4
count()Counts occurrences"banana".count("a") → 3
startswith()Checks starting text"data.csv".startswith("data")
endswith()Checks ending text"data.csv".endswith(".csv")
► String Methods in Practice
email = "  STUDENT@GMAIL.COM  "
clean_email = email.strip().lower()
print(clean_email)

course = "Digital Marketing, SEO, Google Ads"
skills = course.split(", ")
print(skills)
Output
student@gmail.com
['Digital Marketing', 'SEO', 'Google Ads']
ℹ Real-World Use Case
Cleaning messy Excel/CSV data (extra spaces, mixed case emails) using strip() and lower() is one of the most common real tasks a data analyst performs before any analysis begins.

3.7  Practical Exercises

Basic (5 Questions)

1. Store your full name in a string and print its length using len().

2. Print the first and last character of your name using indexing.

3. Convert your name to all uppercase and all lowercase.

4. Use slicing to print only the first 3 letters of 'Samantus'.

5. Use an escape character to print your name and course on two separate lines.

Intermediate (5 Questions)

1. Take a sentence as input and print it in reverse using slicing.

2. Clean a messy string with extra spaces and mixed case using strip() and lower().

3. Split a comma-separated string of skills into a list and print each skill on its own line.

4. Use replace() to change all occurrences of one word in a sentence to another word.

5. Write an f-string that combines a student's name, course, and fee into one formatted sentence.

Advanced (5 Questions)

1. Write a program to check if a given string is a palindrome (reads the same forwards and backwards).

2. Count how many times a specific letter appears in a paragraph of text.

3. Take a full email address and extract just the username part (before the @) using slicing or split().

4. Write a program that takes a sentence and capitalizes the first letter of every word.

5. Build a simple 'Data Cleaner': take a messy string with extra spaces/mixed case and return a clean, title-cased version.

3.8  Module Quiz (MCQs)

Q1. What is the index of the first character in a Python string?

Q2. What does "Data"[::-1] return?

Q3. Which method removes extra spaces from both ends of a string?

Q4. Which escape character creates a new line?

Q5. Which is the modern recommended way to format strings?

ℹ Answer Key
1-b, 2-c, 3-c, 4-b, 5-c

3.9  Module Assignment

Assignment: Student Data Cleaner

Expected Output: A clean, properly-cased student name and a Python list of their courses, displayed together in one neatly formatted output line.

3.10  Interview Questions — Module 3


3.11  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.