Loading lesson...
Slice, index, and transform text
Slice, index, and transform text
Topics covered: String Indexing, String Slicing, Searching in Strings, String Transformation, F-Strings
Every character in a string has a position number called an index. Python uses zero-based indexing, meaning the first character is at position 0, not position 1. This prints "P", "y", and "n". The characters are at positions 0, 1, and 5 respectively. Zero-Based Indexing Consider the string "Python". Here's how each character is indexed: The last character's index is always the string length minus 1. For a 6-character string, the last index is 5. Negative Indexing Python has a powerful feature: n
Slicing extracts a portion of a string using the syntax [start:end]. The slice includes the start index but excludes the end index. Slice Defaults Negative Slice Indices Negative indices work in slices too, making it easy to extract from the end: Slice Step A third parameter specifies the step (how many characters to skip):
Python provides several ways to search for substrings within a string. Each method has specific use cases. The in Operator The first returns True (@ is in the email). The second returns False (gmail is not). find() and index() This finds @ at position 4, then searches for . starting from position 4, finding it at position 12. The count() Method This returns 3 (three a's), 2 (two "na" occurrences), and 0 (no x's). startswith() and endswith() These methods check if a string begins or ends with a s
Python provides methods to modify strings. Remember: strings are immutable, so these methods return new strings rather than modifying the original. strip(), lstrip(), rstrip() The stripped string is "hello world" with length 11. The original had length 17 including the spaces. You can specify which characters to strip: This removes dollar signs from both ends, giving "99.99". The replace() Method You can limit the number of replacements: This replaces only the first 2 occurrences, giving "1 two
Expressions in F-Strings You can put any expression inside the curly braces, not just variables: The expressions are evaluated, then the results are inserted into the string. Number Formatting F-strings support format specifications for controlling number display: F-strings have largely replaced concatenation as the preferred approach since Python 3.6. String Checking Methods Python provides methods to check string properties. These all return True or False. The username is alphanumeric (True),