DEV Community

Cover image for Strings and Exceptions
Paul Apivat
Paul Apivat

Posted on • Edited on • Originally published at paulapivat.com

Strings and Exceptions

Strings

This is a continuation of my coverage of Data Science from Scratch, by Joel Grus (ch2) where the Python crash course brings us to strings and exceptions.

These topics are more nice-to-know rather than central for data science, so we'll cover them briefly (of course I'll revisit this section if I find that they are more important than I had thought).

For strings, the main concept highlighted is string interpolation where a variable is inserted in a string in some fashion. There are several ways to do this, but the f-string approach is most up-to-date and recommended.

Here are some examples:

# first we'll create variables that are pointed at strings (my first and last names)

first_name = "Paul"
last_name = "Apivat"

# f-string (recommended)
f_string = f"{first_name} {last_name}"

# string addition, 'Paul Apivat'
string_addition = first_name + " " + last_name

# string format, 'Paul Apivat'
string_format = "{0} {1}".format(first_name, last_name)

# percent format (NOT recommended), 'Paul Apivat'
pct_format = "%s %s" %('Paul','Apivat')

Enter fullscreen mode Exit fullscreen mode

Exceptions

The author covers exceptions to make the point that they’re not all that bad in Python and it’s worth handling exceptions yourself to make code more readable. Here’s my own example that’s slightly different from the book:

integer_list = [1,2,3]

heterogeneous_list = ["string", 0.1, True]

# you can sum a list of integers, here 1 + 2 + 3 = 6
sum(integer_list)

# but you cannot sum a list of heterogeneous data types
# doing so raises a TypeError
sum(heterogeneous_list)

# the error crashes your program and is not fun to look at
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-3287dd0c6c22> in <module>
----> 1 sum(heterogeneous_list)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

# so the idea is to handle the exceptions with your own messages
try:
    sum(heterogeneous_list)
except TypeError:
    print("cannot add objects of different data types")

Enter fullscreen mode Exit fullscreen mode

At this point, the primary benefit to handling exceptions may be for code readability, so we'll come back to this section if we see more useful examples.

Top comments (0)