Lesson 5 · Python data types deep dive
Python Strings Explained: Slicing, Methods & f-Strings | Data Types #5
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…
- 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.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



