Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Set string in custom format
#1
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,
Reply
#2
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'
Gribouillis likes this post
Reply
#3
I will try it ,
Thank you !
Reply
#4
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)
... 
snippsat likes this post
Reply
#5
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Format String NewPi 2 908 Oct-10-2022, 05:50 PM
Last Post: NewPi
  TypeError: not enough arguments for format string MaartenRo 6 2,858 Jan-09-2022, 06:46 PM
Last Post: ibreeden
  string format challenge jfc 2 1,741 Oct-23-2021, 10:30 AM
Last Post: ibreeden
  Print first day of the week as string in date format MyerzzD 2 1,979 Sep-29-2021, 06:43 AM
Last Post: MyerzzD
  string.format() suddenly causing errors with google drive API zwitrader 0 1,733 Jun-28-2021, 11:38 PM
Last Post: zwitrader
  String to Date format SAF 2 2,412 Apr-06-2021, 02:09 PM
Last Post: snippsat
Smile Set 'Time' format cell when writing data to excel and not 'custom' limors 3 6,195 Mar-29-2021, 09:36 PM
Last Post: Larz60+
  MySQLdb._exceptions.ProgrammingError: not enough arguments for format string. farah97 0 3,297 Jan-22-2020, 03:49 AM
Last Post: farah97
  Highlight/Underline a string | ValueError: zero length field name in format searching1 1 2,987 Jul-01-2019, 03:06 AM
Last Post: metulburr
  write image into string format into text file venkat18 2 4,347 Jun-01-2019, 06:46 AM
Last Post: venkat18

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020