· python til

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:

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())
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket