Index & Slice Lab
Type a string and a Python indexing or slicing expression — [3], [-1], [0:8], [-7:], [::-1], [0:15:2] — and watch the ruler highlight exactly which characters get selected.
Try Indexing / Slicing
● liveString Creation
A string in Python is a sequence of characters enclosed within single quotes, double quotes, or triple quotes. Strings can include letters, digits, special characters, and spaces. Python has no separate character type — a character is simply a string of length one.
Quoting Styles
'Hello World' "Python123!" '''This is a multiline string with three single quotes''' """This is a multiline string with three double quotes"""
Why Different Quotes?
Single quotes make it easy to embed double quotes inside a string, and vice versa. Triple quotes are used for multiline strings or docstrings — they preserve line breaks and indentation exactly as typed.
The white space at index 7 and 10 is also counted as a character. Strings are immutable — once created, their contents cannot be changed directly. Any operation that appears to modify a string actually creates a new string object in memory.
The input() Function
The input() function is a built-in method used to collect user input during program execution — it pauses the program until the user enters data and presses Enter.
The prompt Parameter
Optional. If provided, it is displayed as a message before the user types the input. Whatever is typed is stored — always as a string — in the variable var.
Reading and Displaying
myname = input("Enter your name") print("Welcome", myname)
Run: Enter your name Anil → Output: Welcome Anil
Python f-strings
f-strings provide a simple, readable way to format and embed variables and expressions inside string literals. They are identified by the letter f or F placed immediately before the opening quotation mark.
The variable or expression to embed is placed inside curly braces { } within the string. Python evaluates the contents of the braces at runtime and converts the result to a string. Simple Python expressions can go inside the braces too — including format specifiers like .2f for two decimal places.
The expression price * (1 + tax_rate) evaluates to 21.589199999999998. The :.2f inside the f-string formats that value to two decimal places, giving 21.59.
Accessing Characters and Indexing
Each character in a string is accessible using its index number. Indexing starts at 0 from the left. Negative indexing accesses characters from the right, where -1 is always the index of the last character.
| Positive Indices | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| name | P | y | t | h | o | n |
| Negative Indices | -6 | -5 | -4 | -3 | -2 | -1 |
The index should always be an integer, positive or negative. name[0] points to the first character, name[2] points to the character at positive index 2, and name[-1] points to the last character.
String Slicing
String slicing extracts a portion (substring) of a string by specifying start, end, and optionally step indices, separated by colons within square brackets.
start
The index where slicing begins. If omitted, slicing starts from index 0. This parameter is inclusive — the character at the specified index is selected.
end
The index at which slicing stops. If omitted, slicing goes to the end of the string. This parameter is exclusive — the character at this index is excluded.
step
The interval between characters — optional, default 1. A step of 2 skips every second character. A negative step slices the string in reverse order.
8.5.1 Slicing Using Positive Index
8.5.2 Slicing Using Negative Index
8.5.3 Use of step in Slicing
A positive step moves forward through the string; a negative step moves backward. text[::-1] is the classic idiom for reversing an entire string.
String Traversal
String traversal is the process of accessing each character in a string one by one. The most common way to traverse a string in Python is with a for loop, which reads characters from left to right.
When the for loop starts, the first character at index 0 of A is assigned to i and printed. In the next iteration, the character at index 1 is accessed, and so on until the end of the string. Traversal is useful for searching a character, counting occurrences, or processing characters one at a time.
String Operations
Python supports concatenation, repetition, membership testing, and relational comparison as operations on strings.
| Operation | Operator | Process |
|---|---|---|
| Concatenation | + | Joins two strings |
| Repetition | * | Repeats the string multiple times |
| Membership | in, not in | Checks the presence of a substring |
Relational Operators
The relational operators >, <, >=, <=, ==, != compare strings alphabetically, based on Unicode point values. Comparisons are case sensitive — since upper-case letters have lower Unicode values than lower-case letters.
| Operator | Description | Example | Result |
|---|---|---|---|
| == | Equal to | "apple" == "apple" | True |
| != | Not equal to | "apple" != "Apple" | True |
| < | Alphabetically smaller | "apple" < "banana" | True |
| > | Alphabetically bigger | "apple" > "banana" | False |
| <= | Less than or equal to | "a" <= "A" | False |
| >= | Greater than or equal to | "curd" >= "milk" | False |
Concatenation +
firstname + lastname + info
Joins strings and generates a new string, e.g. combining "Guido", "van Rossum" and a description into one sentence.
Repetition *
"India" * 3 → 'IndiaIndiaIndia'
Repeats a string a specified number of times.
Membership
"He" in "Hello" → True
Checks whether a substring is present inside another string; returns a Boolean value.
Built-in String Functions
Python's built-in string functions are attached to string objects for tasks like formatting, searching, and validation — each returns a new string object or a Boolean value.
Try a String Function
● live| Function | Description | Example Code | Output |
|---|---|---|---|
| capitalize() | Converts the first character of the string to uppercase | "hello".capitalize() | 'Hello' |
| count() | Counts the occurrences of a substring in another string | "banana".count("a") | 3 |
| find() | Finds the first index of a substring (-1 if not found) | "apple".find("p") | 1 |
| index() | Returns the index of a substring (raises error if not found) | "pineapple".index("e") | 4 |
| len() | Returns the number of characters in the string | len("Hello World") | 11 |
| replace() | Replaces a substring with another substring | 'hello world'.replace('world','Python') | 'hello Python' |
| startswith() | Returns True if the string starts with the specified substring | "hello".startswith("he") | True |
| endswith() | Returns True if the string ends with the specified substring | "hello".endswith("hi") | False |
Application of Strings
Worked programs showing how string creation, indexing, slicing, traversal, and built-in functions come together in real code.
Problem 8.1 — Reverse a String
Uses the slicing operation [::-1] to reverse the order of characters in the input string.
Problem 8.2 — Count the Vowels in a String
Lists all vowels (both cases), sets a counter to zero, then traverses the sentence character by character, incrementing the counter whenever a character is a vowel.
Problem 8.3 — Find and Replace a Substring
The replace() method is used twice — once to substitute the name placeholder, once to substitute the item count (converted to a string with str()).
Problem 8.4 — Length of a String Without Built-in Functions
A for loop traverses the string one character at a time, incrementing count on every iteration — demonstrating how a loop performs a cumulative operation over a sequence, without relying on len().
Quick Recap
Tap a question to reveal the answer.
For string = "Python programming", what does string[7:] give?
'programming' — slicing starts at index 7 (the space is index 6, so index 7 is 'p') and continues to the end since the end parameter is omitted.
What does string[-11:-1] give for "Python programming"?
'programmin' — extraction starts 11 characters back from the end and stops just before the last character (index -1 excluded).
What does string[::-1] give?
'gnimmargorp nohtyP' — omitting start and end but giving a step of -1 reverses the entire string.
Why are strings called immutable in Python?
Because once a string is created, its contents cannot be changed in place. Any operation that appears to modify a string — like concatenation or replace() — actually creates a brand new string object in memory; the original is left untouched.
What is the difference between find() and index() when the substring is not present?
find() returns -1 quietly, while index() raises a ValueError and stops the program unless the error is handled.
Write a function to count how many times "sh" occurs as a substring of "she sells seashells by the seashore". What's the expected output, and how would you generalise it for any two strings?
The expected output is 3. A general function can traverse the first string with a loop, take a slice of the same length as the second string starting at each index, and increment a counter whenever that slice equals the second string — Python's own count() method does exactly this internally.
How does a Caesar Cipher shift work, e.g. shifting "ATTACK AT DAWN" by 3?
Each letter is replaced by the letter a fixed number of positions later in the alphabet (wrapping from 'Z' back to 'A'). With a shift of 3, "ATTACK AT DAWN" becomes "DWWDFN DW GDZQ" — a function typically finds each character's position (e.g. using ord()), adds the shift with wraparound using the modulus operator, and converts back to a character (e.g. using chr()).
Why does "apple" <= "A" evaluate to False?
String comparison is based on Unicode values and is case sensitive. Upper-case letters have lower Unicode values than lower-case letters, so any string starting with a lower-case letter (like "apple") is considered alphabetically "greater than" one starting with an upper-case letter (like "A").
What is the index of the last character in a string of length n, using positive and negative indexing?
Positive indexing: n-1. Negative indexing: -1. Both refer to the same, last character of the string.
In string_name[start:end:step], what happens if step is negative but start and end are left in their normal left-to-right order (e.g. [0:7:-1])?
It returns an empty string — a negative step moves backward through the string, so start must be greater than or equal to end (e.g. [7:0:-1]) for any characters to be selected.