Mathew K Analytics

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…

⬇ Download notebook🧠 Quiz & exercises

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python 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)
<class 'str'>
5
Hello
HELLO

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)
single quotes | double quotes, letting 'these' through
a genuine
multi-line string
Line one
Line two	Tabbed
C:\Users\name\no_escapes_here
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')
Ana is 29 years old
ANA is 58 in dog years, sort of
concatenated with plus
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])
P
n
yth
Pyt
hon
nohtyP
Pto

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())
THE QUICK BROWN FOX
the quick brown fox
The quick brown fox
The Quick Brown Fox
THE qUICK brown FOX
strasse
strasse

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())
True
False
True
True
False
False

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))
[    hi    ]
[****hi****]
[hi        ]
[        hi]
00042
-0042

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('*'))
[padded text]
[padded text   ]
[   padded text]
hello
important

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))
0
31
-1
0
10
sentence = 'the quick brown fox'
try:
    sentence.index('cat')
except ValueError as e:
    print(f'Caught: {e}')
Caught: substring not found

Part 9: count()#

text = 'mississippi'
print(text.count('s'))
print(text.count('ss'))
print(text.count('i'))
print(text.count('iss'))
4
2
4
2

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'))
True
True
True
False

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())
['apple', 'banana', 'cherry', 'date']
['apple', 'banana', 'cherry,date']
['apple,banana,cherry', 'date']
['spaced', 'out', 'words']
multiline = 'line one\nline two\r\nline three'
print(multiline.splitlines())
print(multiline.splitlines(keepends=True))
['line one', 'line two', 'line three']
['line one\n', 'line two\r\n', 'line three']
url = 'user@example.com'
print(url.partition('@'))
print(url.rpartition('@'))
path = 'a/b/c/d'
print(path.rpartition('/'))
('user', '@', 'example.com')
('user', '@', 'example.com')
('a/b/c', '/', 'd')

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)))
the quick brown fox
the, quick, brown, fox
thequickbrownfox
0-1-2-3-4

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'))
THE cat sat on THE mat
THE cat sat on the mat
the cog sog on the mog

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())
True
False
True
True
True
True
False
True
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())
True
True
True
False
True
False
True
False
False

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))
Ana is 29 years old
Sam scored 95 points
first comes before second
3.14
data = {'name': 'Chen', 'role': 'engineer', 'extra': 'unused'}
template = '{name} works as an {role}'
print(template.format_map(data))
Chen works as an engineer

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))
thE qUIck brOwn fOx
th qck brwn fx
uryyb

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}')
b'caf\xc3\xa9'
b'caf'
b'caf?'
Caught: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)

Part 18: expandtabs()#

row = 'name\tage\tcity'
print(row)
print(repr(row.expandtabs()))
print(repr(row.expandtabs(4)))
print(repr(row.expandtabs(2)))
name	age	city
'name    age     city'
'name    age city'
'name  age city'

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'))
report.txt
test_report.txt
test_report
test_report.txt

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)
Caught: 'str' object does not support item assignment
Hello

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)
this is genuinely slow
this is genuinely slow
print('10' < '9')
print('apple' < 'banana')
print('Apple' < 'apple')
print(sorted(['10', '9', '2', '1']))
print(sorted([10, 9, 2, 1]))
True
True
True
['1', '10', '2', '9']
[1, 2, 9, 10]

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.

  1. What does this print?

    s = 'mississippi'
    print(s.count('ss'), s.rfind('ss'))
    
  2. What does this print?

    print('a,b,,c'.split(','))
    
  3. What happens when you run word = 'hello' and then word[0] = 'H'?

  4. What does this print?

    print('Python'[::-2])
    
  5. What does this print?

    print(sorted(['10', '9', '2', '1']))
    

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. 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(",", ""))
    
  2. 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")
    
  3. 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.