1

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?

Mackrell
  • 11
  • 2
  • Is there any specific pattern after which you want to add hyphens? – ashishmishra Dec 17 '19 at 13:23
  • 1
    It varies depending on publisher. For my publisher, the pattern is the one above - 3-1-3-5-1 – Mackrell Dec 17 '19 at 13:25
  • 1
    Does this answer your question? [How to automatically apply ISBN hyphenation?](https://stackoverflow.com/questions/4154708/how-to-automatically-apply-isbn-hyphenation) – Georgy Dec 17 '19 at 13:34
  • Thanks, Georgy. My needs are pretty simple in this case, so I didn't really look into any third party libraries, but some of these are pretty useful. – Mackrell Dec 17 '19 at 13:38

5 Answers5

4

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

return "-".join([isbn[0:3], isbn[3], isbn[4:7], isbn[7:12], isbn[12]])
AKX
  • 152,115
  • 15
  • 115
  • 172
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]}"
Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
0

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thanks That approach is easier than counting the characters in string slicing.. – Mackrell Dec 17 '19 at 13:33
  • @Mackrell I checked the other answers, and mine requires about 70 characters of typing, while AKX`s answer only needs 53, so what I gave is more verbose at least in that regard. – Tim Biegeleisen Dec 17 '19 at 13:34
  • Yeah, but counting the characters took me longer than typing those extra 17 characters! – Mackrell Dec 17 '19 at 13:40
0

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()
chepner
  • 497,756
  • 71
  • 530
  • 681
0

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.

Coukaratcha
  • 133
  • 2
  • 11