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

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?



Solution 1:[1]

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

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

Solution 2:[2]

If you want to use string formatting as mentioned:

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

Solution 3:[3]

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

Solution 4:[4]

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()

Solution 5:[5]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKX
Solution 2 Joshua Fox
Solution 3
Solution 4 chepner
Solution 5 Coukaratcha