Lesson 5 · Python data types deep dive
Python Strings Explained: Slicing, Methods & f-Strings | Data Types #5
Str, the largest built-in type by method count, and the most-used type in nearly every real Python program. Every literal form, indexing and slicing, and…
- CoursePython data types deep dive
- Lesson5 of 12
- Video35 min
- FormatJupyter notebook · 28 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbPython Data Types Deep-Dive, Video 5: Strings (str)#
- Video five of the twelve-part series: str, the largest built-in type by method count, and the most-used type in nearly every real Python program.
- Every literal form, indexing and slicing, and all forty-seven public str methods, one at a time.
- This is the longest video in the series. Let's get into it.
Part 1: What Makes str Different#
greeting = 'Hello'
print(type(greeting))
print(len(greeting))
upper_version = greeting.upper()
print(greeting)
print(upper_version)
Part 2: String Literals#
single = 'single quotes'
double = "double quotes, letting 'these' through"
triple = '''a genuine
multi-line string'''
escaped = 'Line one\nLine two\tTabbed'
raw = r'C:\Users\name\no_escapes_here'
print(single, double, sep=' | ')
print(triple)
print(escaped)
print(raw)
name = 'Ana'
age = 29
print(f'{name} is {age} years old')
print(f'{name.upper()} is {age * 2} in dog years, sort of')
print('concatenated ' + 'with plus')
print('implicit' ' concatenation')
Part 3: Indexing and Slicing#
word = 'Python'
print(word[0])
print(word[-1])
print(word[1:4])
print(word[:3])
print(word[3:])
print(word[::-1])
print(word[::2])
Part 4: Case-Changing Methods#
text = 'the Quick BROWN fox'
print(text.upper())
print(text.lower())
print(text.capitalize())
print(text.title())
print(text.swapcase())
print('STRASSE'.casefold())
print('STRASSE'.lower())
Part 5: Case-Checking Methods#
print('HELLO'.isupper())
print('Hello'.isupper())
print('hello'.islower())
print('Hello World'.istitle())
print('Hello world'.istitle())
print('123'.isupper())
Part 6: Alignment and Padding Methods#
word = 'hi'
print(f'[{word.center(10)}]')
print(f'[{word.center(10, chr(42))}]')
print(f'[{word.ljust(10)}]')
print(f'[{word.rjust(10)}]')
print('42'.zfill(5))
print('-42'.zfill(5))
Part 7: Stripping Methods#
messy = ' padded text '
print(f'[{messy.strip()}]')
print(f'[{messy.lstrip()}]')
print(f'[{messy.rstrip()}]')
print('xxxhelloxxx'.strip('x'))
print('***important***'.strip('*'))
Part 8: Searching Methods#
sentence = 'the quick brown fox jumps over the lazy dog'
print(sentence.find('the'))
print(sentence.rfind('the'))
print(sentence.find('cat'))
print(sentence.index('the'))
print(sentence.find('brown', 10))
sentence = 'the quick brown fox'
try:
sentence.index('cat')
except ValueError as e:
print(f'Caught: {e}')
Part 9: count()#
text = 'mississippi'
print(text.count('s'))
print(text.count('ss'))
print(text.count('i'))
print(text.count('iss'))
Part 10: startswith() and endswith()#
filename = 'report_final.pdf'
print(filename.startswith('report'))
print(filename.endswith('.pdf'))
print(filename.endswith(('.pdf', '.docx', '.txt')))
print(filename.endswith('.csv'))
Part 11: Splitting Methods#
csv_row = 'apple,banana,cherry,date'
print(csv_row.split(','))
print(csv_row.split(',', 2))
print(csv_row.rsplit(',', 1))
print(' spaced out words '.split())
multiline = 'line one\nline two\r\nline three'
print(multiline.splitlines())
print(multiline.splitlines(keepends=True))
url = 'user@example.com'
print(url.partition('@'))
print(url.rpartition('@'))
path = 'a/b/c/d'
print(path.rpartition('/'))
Part 12: join()#
words = ['the', 'quick', 'brown', 'fox']
print(' '.join(words))
print(', '.join(words))
print(''.join(words))
print('-'.join(str(n) for n in range(5)))
Part 13: replace()#
text = 'the cat sat on the mat'
print(text.replace('the', 'THE'))
print(text.replace('the', 'THE', 1))
print(text.replace('at', 'og'))
Part 14: Character Classification Methods#
print('Python3'.isalnum())
print('Python 3'.isalnum())
print('Python'.isalpha())
print('123'.isdigit())
print('123'.isdecimal())
print('\u00b2'.isdigit())
print('\u00b2'.isdecimal())
print('\u00bd'.isnumeric())
print(' '.isspace())
print('\t\n'.isspace())
print('hello'.isascii())
print('caf\u00e9'.isascii())
print('hello world'.isprintable())
print('hello\n'.isprintable())
print('variable_name'.isidentifier())
print('2variable'.isidentifier())
print(''.isalnum())
Part 15: format() and format_map()#
template = '{} is {} years old'
print(template.format('Ana', 29))
named_template = '{name} scored {score} points'
print(named_template.format(name='Sam', score=95))
indexed_template = '{1} comes before {0}'
print(indexed_template.format('second', 'first'))
print('{:.2f}'.format(3.14159))
data = {'name': 'Chen', 'role': 'engineer', 'extra': 'unused'}
template = '{name} works as an {role}'
print(template.format_map(data))
Part 16: translate() and maketrans()#
table = str.maketrans('aeiou', 'AEIOU')
print('the quick brown fox'.translate(table))
remove_table = str.maketrans('', '', 'aeiou')
print('the quick brown fox'.translate(remove_table))
rot13_table = str.maketrans(
'abcdefghijklmnopqrstuvwxyz',
'nopqrstuvwxyzabcdefghijklm'
)
print('hello'.translate(rot13_table))
Part 17: encode()#
text = 'caf\u00e9'
print(text.encode('utf-8'))
print(text.encode('ascii', errors='ignore'))
print(text.encode('ascii', errors='replace'))
try:
text.encode('ascii')
except UnicodeEncodeError as e:
print(f'Caught: {e}')
Part 18: expandtabs()#
row = 'name\tage\tcity'
print(row)
print(repr(row.expandtabs()))
print(repr(row.expandtabs(4)))
print(repr(row.expandtabs(2)))
Part 19: removeprefix() and removesuffix()#
filename = 'test_report.txt'
print(filename.removeprefix('test_'))
print(filename.removeprefix('nope_'))
print(filename.removesuffix('.txt'))
print(filename.removesuffix('.pdf'))
Part 20: Immutability in Practice#
word = 'hello'
try:
word[0] = 'H'
except TypeError as e:
print(f'Caught: {e}')
word = 'H' + word[1:]
print(word)
Part 21: Common Patterns and Pitfalls#
words = ['this', 'is', 'genuinely', 'slow']
result = ''
for word in words:
result += word + ' '
print(result.strip())
fast_result = ' '.join(words)
print(fast_result)
print('10' < '9')
print('apple' < 'banana')
print('Apple' < 'apple')
print(sorted(['10', '9', '2', '1']))
print(sorted([10, 9, 2, 1]))
Wrap-Up: What You Learned#
- String literals, escape sequences, raw strings, f-strings, and indexing/slicing.
- Case methods: upper, lower, capitalize, title, swapcase, casefold, isupper, islower, istitle.
- Padding and stripping: center, ljust, rjust, zfill, strip, lstrip, rstrip.
- Searching and counting: find, rfind, index, rindex, count, startswith, endswith.
- Splitting and joining: split, rsplit, splitlines, partition, rpartition, join, replace.
- All nine character classification methods, from isalnum to isidentifier.
- Templating with format and format_map, translate and maketrans, encode, expandtabs, removeprefix, and removesuffix.
- Immutability, efficient string building with join, and lexicographic versus numeric sorting.
- That's all forty-seven public str methods covered. Next up: list, the workhorse mutable sequence type.
🧠 Test yourself
Pick an answer to check it. Your best score is saved in this browser.
What does this print?
s = 'mississippi' print(s.count('ss'), s.rfind('ss'))
'ss' appears twice, and the last one starts at index 5. rfind searches from the right.
What does this print?
print('a,b,,c'.split(','))
split with an explicit separator keeps empty strings between adjacent separators.
What happens when you run
word = 'hello'and thenword[0] = 'H'?Strings cannot be changed in place. Build a new one instead, for example
'H' + word[1:].What does this print?
print('Python'[::-2])
A step of -2 starts at the last character and takes every second one backwards: n, h, y.
What does this print?
print(sorted(['10', '9', '2', '1']))
Strings sort character by character, so '10' comes before '2'. Convert to int for numeric order.
💻 Practice exercises
Try each one in the notebook or in your own editor before opening the solution.
Given text = ' Hello, World ', print it stripped and uppercased, then print the stripped version with the comma removed using replace.
💡 Hint
Chain strip() with upper(), and use replace(',', '').
✅ Show solution
text = " Hello, World " print(text.strip().upper()) print(text.strip().replace(",", ""))
Write is_palindrome(s) that ignores case, spaces and punctuation. 'A man, a plan, a canal: Panama' should be True.
💡 Hint
Keep only the alphanumeric characters (isalnum), lowercase them, and compare with the reverse.
✅ Show solution
def is_palindrome(s): cleaned = "".join(ch.lower() for ch in s if ch.isalnum()) return cleaned == cleaned[::-1] print(is_palindrome("A man, a plan, a canal: Panama")) assert is_palindrome("A man, a plan, a canal: Panama") assert not is_palindrome("hello")
Count how often each word appears in a sentence (ignore case and punctuation), then print a report with each word left-aligned in a 10-character column and its count right-aligned in 3 characters, most common first.
💡 Hint
Strip punctuation with strip('.,!?'), then use ljust and rjust (or f-string alignment) when printing.
✅ Show solution
text = "The cat and the hat. The end, and the start!" counts = {} for raw in text.split(): word = raw.strip(".,!?").lower() counts[word] = counts.get(word, 0) + 1 # most common first, ties alphabetical for word, n in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])): print(word.ljust(10) + str(n).rjust(3)) assert counts["the"] == 4
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



