Python Strings - Easy & Detailed Notes
1. Python Strings
Strings are sequences of Unicode characters enclosed in single, double, or triple quotes.
Immutable: cannot be changed after creation.
Examples: 'Hello', "Hi", '''multi line'''. Indexing starts at 0; negative indexes from end.
2. Slicing Strings
Syntax: s[start:stop:step]. Start inclusive, stop exclusive. Cases: s[:], s[:5], s[2:], s[1:7:2], s[::-1]
(reverse), negative indexes: s[-5:-1], omitted values use defaults. Out-of-range indexes do not raise
errors.
3. Modify Strings
Since immutable, methods return new strings. Common: upper(), lower(), strip(), replace(), split(),
capitalize(), title(), swapcase(), casefold().
4. Concatenate Strings
Use + to join, * to repeat. Example: 'Py'+'thon'='Python'; 'Hi'*3='HiHiHi'. join() efficiently joins
iterable: ','.join(['a','b']).
5. Format Strings
Use f-strings: f'Name: {name}'. Expressions allowed: f'{2+3}'. Format specifiers: {pi:.2f}, {n:,},
{x:>10}, {x:<10}, {x:^10}. Also format() and % formatting (legacy).
6. Escape Characters
\\ backslash, \' single quote, \" double quote, \n newline, \t tab, \r carriage return, \b backspace. Raw
strings: r'C:\new\test' ignore escapes except ending backslash.
7. String Methods
Frequently used: len(), find(), index(), count(), startswith(), endswith(), isalpha(), isdigit(), isalnum(),
isspace(), split(), join(), replace(), strip(), lstrip(), rstrip(), upper(), lower(), title(), capitalize(),
swapcase(), center(), ljust(), rjust(), zfill(), encode(). Note: index() raises ValueError if not found;
find() returns -1.