Is there an easy way to add dashes to an ISBN in Python?

618 views Asked by At

I have a column of 13 digit ISBN numbers (e.g. 1234567890123) saved as strings. To display them in a report, I need to add hyphens, e.g. (123-4-567-89012-3). I use a function to add the dashes before displaying, e.g.

def format_isbn(isbn):
    return isbn[0:3] + "-" + isbn[3] + "-" + isbn[4:7] + "-" + isbn[7:12] + "-" + isbn[12]

Is there a simpler way that I'm missing, perhaps by using string formatting?

5

There are 5 answers

1
AKX On

Not really, aside from maybe using "-".join():

return "-".join([isbn[0:3], isbn[3], isbn[4:7], isbn[7:12], isbn[12]])
0
Joshua Fox On

If you want to use string formatting as mentioned:

return f"{isbn[0:3]}-{isbn[3]}-{isbn[4:7]}-{isbn[7:12]}-isbn[12]}"
3
Tim Biegeleisen On

You could use re.sub here for a regex option:

isbn = "1234567890123"
output = re.sub(r'(\d{3})(\d{1})(\d{3})(\d{5})(\d{1})', '\\1-\\2-\\3-\\4-\\5', isbn)
print(output)

This prints:

123-4-567-89012-3
0
chepner On

struct.unpack would be nice if it didn't force you to work with a bytes value.

import struct


def format_isbn(n: str):
    fmt = struct.Struct("3s s 3s 5s s")
    return b'-'.join(fmt.unpack(n.encode())).decode()
0
Coukaratcha On

No. You cannot.

ISBN-13 use the following format: <GSI-prefix>-<zone code>-<publisher code>-<publication code>-<checksum>

Publisher code can be a 2 to 7 digits number. You cannot tell just by reading the whole ISBN code.