Loops and Strings
1. Python Loops & Iteration
Section titled “1. Python Loops & Iteration”Python provides two primary loop structures and a one-line concise method.
whileloop: Executes a block of code continuously as long as a given condition remainsTrue. (e.g.,while i > 0:).forloop: Iterates over a sequence (like a range, list, or string). (e.g.,for i in range(10):).- List Comprehension: A one-line shorthand to generate lists using a
forloop.- Syntax:
[i for i in range(10)]$\rightarrow$ creates[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
- Syntax:
Loop Control Statements:
break: Instantly terminates the entire loop. Program control jumps to the first statement immediately following the loop body.continue: Instantly skips the rest of the code in the current iteration only. The loop does not terminate; it jumps back to the top to evaluate the next iteration.
The else Clause in Loops:
Both while and for loops can have an optional else block appended to them.
- How it works: The
elseblock executes only if the loop completes normally (i.e., thewhilecondition naturally becomesFalse, or theforloop reaches the end of its iterable). - The Catch: If the loop is terminated prematurely by a
breakorreturnstatement, theelseblock is completely bypassed and will not execute.
2. String Indexing & Slicing
Section titled “2. String Indexing & Slicing”Strings are sequences of characters. Python uses 0-based indexing (the first character is always at index 0).
Indexing (Extracting single characters):
- Positive Indexing:
string[0]gets the first character,string[3]gets the fourth. - Negative Indexing: Python counts backwards from the end.
string[-1]always gets the last character,string[-2]is the second to last.
Slicing (Extracting substrings):
- Syntax:
string[start:stop:step]. It extracts starting at thestartindex and stops immediately before thestopindex (thestopindex is not included). - Omitting Bounds: *
string[1:]extracts from index 1 to the very end.string[:3]extracts from the beginning up to index 2.
- Out-of-Bounds Safety: If you provide a slice index larger than the string’s length, Python does not throw an error; it safely treats it as the maximum length of the string.
- Steps:
string[1:-1:2]extracts characters from index 1 to the second-to-last character, skipping every other character. - Common Slicing Idioms:
- Copying:
string[:]creates a full, exact copy of the string. - Reversing:
string[::-1]is the standard Pythonic way to reverse a string.
- Copying:
3. String Formatting & Raw Strings
Section titled “3. String Formatting & Raw Strings”Python offers three main ways to inject variables into strings.
- f-strings (Modern/Best Practice): Prepend the string with
fand put expressions in curly braces.print(f"{a}+{b}={a+b}")
.format()Method: * Positional:'{0} and {1}'.format('minced meat', 'eggs')- Keyword:
'{food}'.format(food='stuffing') - Mixed:
'{0}, {other}'.format('Billi', other='Georg')
- Keyword:
%Formatting (Legacy): Uses%sfor strings,%dfor integers, and%ffor floats."String: %s int %d" % ('str', 57)
Raw Strings:
- Prefixed with an
r(e.g.,r'C:\nowhere'). - Purpose: They treat backslashes
\as literal characters rather than escape characters (like\nfor newline). Highly useful for writing Windows file paths or Regular Expressions.
4. Top 10 Essential String Methods
Section titled “4. Top 10 Essential String Methods”As requested, since the text omitted them, here are the 10 most critical built-in string methods you must know:
.lower()/.upper(): Converts the entire string to lowercase or uppercase..strip(): Removes leading and trailing whitespace (or specific characters) from the string..split(separator): Splits a string into a list of substrings based on a delimiter (defaults to splitting by spaces)..join(iterable): The opposite of split. Joins a list of strings into one single string, using the calling string as the separator (e.g.,"-".join(["a", "b"])$\rightarrow$"a-b")..replace(old, new): Replaces all occurrences of a specified substring with a new substring..find(substring): Returns the lowest index where the substring is found. Returns1if not found (unlike.index()which throws an error)..count(substring): Returns the total number of non-overlapping occurrences of a substring..startswith(prefix): ReturnsTrueif the string starts with the specified prefix..endswith(suffix): ReturnsTrueif the string ends with the specified suffix..isalpha()/.isdigit(): ReturnsTrueif all characters in the string are in the alphabet / are numbers, respectively.