Reputation: 11
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?
Upvotes: 1
Views: 676
Reputation: 183
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.
Upvotes: 0
Reputation: 530960
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()
Upvotes: 0
Reputation: 520948
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
Upvotes: 0
Reputation: 19655
If you want to use string formatting as mentioned:
return f"{isbn[0:3]}-{isbn[3]}-{isbn[4:7]}-{isbn[7:12]}-isbn[12]}"
Upvotes: 2
Reputation: 168863
Not really, aside from maybe using "-".join()
:
return "-".join([isbn[0:3], isbn[3], isbn[4:7], isbn[7:12], isbn[12]])
Upvotes: 4