What I Learned at Work this Week: Python Basics

I’ve experienced a lot of great things about working in tech since starting my job in July. One thing that might not be unique to this industry, but is a first for me, is that my company is preparing for a “winter break” where pretty much everything shuts down for a week. (Shout out to the folks who will be on call during this time, may we wish them an uneventful shift). Needless to say, I would enjoy nothing more than a true break where I do nothing that could be considered “work” over the course of a week, but excess isn’t good for anyone, so I’m planning to keep a bit busy by picking up a Python course.

We didn’t study Python at my boot camp, so I was really grateful to find a job where I’d be given the opportunity to prove I could learn it and eventually become proficient. This course was recommended by a coworker who is also working through it. About 4 hours in, I’ve picked up a few basic principles and tricks that might be useful if any readers are also picking up the language (I also learned that Python coders can sometimes be called “pythonistas,” which might not be useful, but is fun).

String Interpolation

The % sign

'This %s can add strings or %s, like %d.' % ('method', 'numbers', 55)

I find it useful to break this line into three parts. The first is the string itself, which contains three placeholders: %s, another %s, and %d. The second part is the % operator, which indicates that these values are placeholders. Without that, we’d simply have a string that includes gibberish symbols between the words. Finally, we provide the arguments that will be used to populate our placeholders.

These arguments must be placed in order and must match the data type declared in the original string. %s is a placeholder for a string value and %d is a placeholder for a number value (integer or floating point). The resulting string here would be:

'This method can add strings or numbers, like 55.'

I can’t tell you the number of times I’ve tried reading Python and had to Google “what is %s Python.” I’m glad that I’ve formally learned the answer, but I also learned that this is something of a “classic” method of Python string interpolation. That’s a relief, because I honestly find it pretty confusing both to read and to write.

The .format() method

'This {0} can also add {2} out of {1}.'.format('method', 'order', 'values')
# 'This method can also add values out of order.'

Again we’ve got three parts, but I’d argue that this is a bit easier to read for an average programmer. We see a string that is peppered with curly brackets with numbers inside. We’ll come to see that these numbers are indexes that indicate what value should be populated in each.

We see that a method, format, is being invoked on our string. The method accepts a series of arguments (three, in this case). If the curly brackets in our string didn’t have index values, the arguments would be printed in the order they appear. The optional indexes allow us to change the order of the arguments’ placements. We can also use one of our values more than once:

'{0} and {0} and {0} {1}'.format('over', 'again')
# 'over and over and over again'

But it gets even better, because we don’t necessarily have to use indexes if we want to be more clear about what we’re referencing:

'My favorite fruit is {favorite}, and my second is {second}.'.format(favorite='bananas',second='blueberries')# 'My favorite fruit is bananas and my second is blueberries'

That’s right, we can build a key/value pair inside of our method’s argument! In this example, we’re providing format with multiple arguments, but if we wanted to clean things up a bit, we could pass in one single object. In Python, an object that contains key/value pairs is called a dictionary:

ourArgument = {'favorite':'bananas','second':'blueberry'}
'I like {favorite} more than {second}.'.format(**ourArgument)
# 'I like bananas more than blueberries.'

We just have to remember to add the double asterisks before our dictionary if we’re using this method.

f-String

shirtSize='large'
pantSize='32x32'
f'I wear a {shirtSize} shirt and {pantSize} pants.'
# I wear a large shirt and 32x32 pants.

There’s not much to explain here — we can drop variables right into our string and they’ll show up. All we have to do is add f (uppercase or lowercase is okay) before our string to activate the logic. Speaking of logic, we can run as much Python as we’d like inside of those curly brackets — that means defined functions, built-in functions, or even something simple like a mathematical operation:

f'The product of 3 and 7 is {3 * 7}.'# ‘The product of 3 and 7 is 21.

Miscellaneous Notes

.split

'This string has spaces.'.split()
// in JS => ['This string has spaces']
# in Python => ['This', 'string', 'has', 'spaces']

Of course if we wanted to split by spaces with JavaScript, we’d simply add an argument of (‘ ‘), but I still think it’s cool that Python has this as the default.

String reversal trick

'hello'[1]
// in JS => 'e'
# in Python => 'e'

If we want a substring in JavaScript, we could use the substring or slice methods. Python doesn’t use substring, but makes our lives much easier by allowing us to index from a range:

'hello'[1:4]
// in JS (this doesn’t work)
# in Python => 'ell'

Awesome! It’s worth noting that this is actually just shorthand for Python’s slice method, but it once again makes our lives easier with improved readability. It therefore might not surprise us to learn that the value after the colon is the end index and is non-inclusive. So we go up to index 4, but don’t include it in our substring. If we leave out the value before the colon, it’ll default to the beginning of the string:

'hello'[:3]
# 'hel'

We’re seeing that Python has some useful defaults when we leave arguments blank. To go along with that, Python’s index logic includes an optional third argument to go along with start point and end point. The third argument represents step — whether we want to step over certain values as we traverse the string. For example, the number 2 means we will step 2 indexes away rather than 1 when building our result:

'hello'[::2]
# 'hlo'

At this risk of giving away the trick — what happens if our third argument is a negative number? Instead of stepping forward that number of spaces, we’ll step backward. So if we take the whole string and re-print it, taking one step backward each time…

'hello'[::-1]# 'olleh'

It’s the Python reverse string trick!

Making the effort

Sources

Solutions Engineer