Python Forum

Full Version: Set string in custom format
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
wanted to know how can I do the following :

I have a function the return 8 digits(as string)
12345678
I want to return it as
123-45-678 
how can I do it ?
is there a "clean" way for it ?
or just use string [:2]-[3:5]-[6:9] ?
Thanks,
Can *unpack it like this,one of the few cases where format() is useful over f-string.
>>> n = '12345678'
>>> req = "{}{}{}-{}{}-{}{}{}".format(*n)
>>> req
'123-45-678'
I will try it ,
Thank you !
I always like to define general tools

>>> import io
>>> 
>>> def multislice(s, sizes):
...     f = io.StringIO(s)
...     return (f.read(n) for n in sizes)
... 
>>> '-'.join(multislice('12345678', (3, 2, 3)))
'123-45-678'
>>> 
An alternative version
>>> def multislice(s, sizes):
...     return map(io.StringIO(s).read, sizes)
... 
here's an updated version of the program that includes several additional features
import tkinter as tk
from tkinter import messagebox

def format_digits(digits):
    if len(digits) != 8:
        messagebox.showerror("Error", "Please enter 8 digits only.")
        return
    if not digits.isdigit():
        messagebox.showerror("Error", "Please enter only numeric characters.")
        return
    return digits[:3] + "-" + digits[3:6] + "-" + digits[6:]

def on_submit():
    digits = entry.get()
    formatted_digits = format_digits(digits)
    if formatted_digits is None:
        return
    label.config(text=formatted_digits)
    entry.delete(0, tk.END)

root = tk.Tk()
root.title("Format Digits")

label = tk.Label(root, text="Enter 8 digits:")
label.pack()

entry = tk.Entry(root)
entry.pack()

submit_button = tk.Button(root, text="Submit", command=on_submit)
submit_button.pack()

result_label = tk.Label(root, text="")
result_label.pack()

clear_button = tk.Button(root, text="Clear", command=lambda: entry.delete(0, tk.END))
clear_button.pack()

root.mainloop()
Input validation: The format_digits function checks if the input string is 8 digits long and contains only numeric characters. If either of these conditions is not met, the function displays an error message using the tkinter messagebox module.

Clear button: A clear button is added that allows the user to clear the input field with a single click.

Input field clears after submit: After the user submits the input, the input field is cleared.

Error Handling: In case of any input validation error, it will show error message with messagebox