Set string in custom format - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Set string in custom format (/thread-39214.html) |
Set string in custom format - korenron - Jan-16-2023 Hello, wanted to know how can I do the following : I have a function the return 8 digits(as string) 12345678I want to return it as 123-45-678how can I do it ? is there a "clean" way for it ? or just use string [:2]-[3:5]-[6:9] ? Thanks, RE: Set string in custom format - snippsat - Jan-16-2023 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' RE: Set string in custom format - korenron - Jan-16-2023 I will try it , Thank you ! RE: Set string in custom format - Gribouillis - Jan-16-2023 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) ... RE: Set string in custom format - mutantGOD - Jan-16-2023 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 |