Skip to content

Loops and Strings

Python provides two primary loop structures and a one-line concise method.

  • while loop: Executes a block of code continuously as long as a given condition remains True. (e.g., while i > 0:).
  • for loop: 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 for loop.
    • Syntax: [i for i in range(10)] $\rightarrow$ creates [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

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 else block executes only if the loop completes normally (i.e., the while condition naturally becomes False, or the for loop reaches the end of its iterable).
  • The Catch: If the loop is terminated prematurely by a break or return statement, the else block is completely bypassed and will not execute.

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 the start index and stops immediately before the stop index (the stop index 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.

Python offers three main ways to inject variables into strings.

  1. f-strings (Modern/Best Practice): Prepend the string with f and put expressions in curly braces.
    • print(f"{a}+{b}={a+b}")
  2. .format() Method: * Positional: '{0} and {1}'.format('minced meat', 'eggs')
    • Keyword: '{food}'.format(food='stuffing')
    • Mixed: '{0}, {other}'.format('Billi', other='Georg')
  3. % Formatting (Legacy): Uses %s for strings, %d for integers, and %f for 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 \n for newline). Highly useful for writing Windows file paths or Regular Expressions.

As requested, since the text omitted them, here are the 10 most critical built-in string methods you must know:

  1. .lower() / .upper(): Converts the entire string to lowercase or uppercase.
  2. .strip(): Removes leading and trailing whitespace (or specific characters) from the string.
  3. .split(separator): Splits a string into a list of substrings based on a delimiter (defaults to splitting by spaces).
  4. .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").
  5. .replace(old, new): Replaces all occurrences of a specified substring with a new substring.
  6. .find(substring): Returns the lowest index where the substring is found. Returns 1 if not found (unlike .index() which throws an error).
  7. .count(substring): Returns the total number of non-overlapping occurrences of a substring.
  8. .startswith(prefix): Returns True if the string starts with the specified prefix.
  9. .endswith(suffix): Returns True if the string ends with the specified suffix.
  10. .isalpha() / .isdigit(): Returns True if all characters in the string are in the alphabet / are numbers, respectively.