Python: Naming slices
Another gem from Fluent Python is that you can name slices. How did I not know that?!
Let’s have a look how it works using an example of a Vehicle Identification Number, which has 17 characters that act as a unique identifier for a vehicle. Different parts of that string mean different things.
So given the following VIN:
vin = "2B3HD46R02H210893"
We can extract components like this:
print(f"""
World manufacturer identifier: {vin[0:3]}
Vehicle Descriptor: {vin[3:9]}
Vehicle Identifier: {vin[9:17]}
""".strip())
If we run this code, we’ll see the following output:
World manufacturer identifier: 2B3
Vehicle Descriptor: HD46R0
Vehicle Identifiern: 2H210893
Let’s say we want to reuse those slices elsewhere in our code.
Maybe when we write the code we can remember what each of the slice indexes mean, but for future us it would help to name them, which we can do using the slice
function.
Our code would then look like this:
world_manufacturer_id = slice(0,3)
vehicle_descriptor = slice(3,9)
vehicle_identifier = slice(9,17)
print(f"""
World manufacturer identifier: {vin[world_manufacturer_id]}
Vehicle Descriptor: {vin[vehicle_descriptor]}
Vehicle Identifier: {vin[vehicle_identifier]}
""".strip())
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.