Python Forum
Dynamic Formatting of String
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamic Formatting of String
#1
I'm having some issues figuring out a way to transform a random number, that ranges from 2-5 characters in length. I'm trying to format the first 3 characters, regardless of spaces, to the following format.

Input = '12345'
Expected_Result = '1 2/3'

This is what I have so far, but it is not dynamic with spaces. Any help will be appreciated.

1
2
3
bit_size= '618'
 
print('{} {}/{}'.format(*bit_size))
Reply
#2
use double slash in print statement.
You need to escape the '/' which is itself an escape character
Reply
#3
(Feb-27-2018, 04:06 AM)Larz60+ Wrote: use double slash in print statement.
You need to escape the '/' which is itself an escape character

So I was able to get a little further after working on it for a few hours, but I'm still hitting a roadblock with allowing for a dynamic input. For example, the below output is constricted by the formatting code I've entered and is giving me a Tuple Index error. Any thoughts on how I can change that to allow for a return of values 1-4 numbers in length?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
size = '13 1/8'
#grabs numeric values in string and concatenates
def get_num(x):
    return str(''.join(ele for ele in x if ele.isdigit()))
 
x = get_num(size)
y = int(x)
 
#rules to remove leading 1s
if int(str(y)[:1]) == 1:
    if int(str(y)[1]) != 1:
        print('{} {}/{}'.format(*x))
    else:
        print('{}{} {}/{}'.format(*x))
else:
    print('{}{} {}/{}'.format(*x))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Formatting DateTime string and and converting it from AM/PM to 24 hours tester_V 2 1,173 Jun-08-2024, 05:16 PM
Last Post: tester_V
  Formatting a date time string read from a csv file DosAtPython 5 5,236 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  String formatting (strptime) issues Henrio 2 1,883 Jan-06-2023, 06:57 PM
Last Post: deanhystad
  confused about string formatting barryjo 7 3,467 Mar-06-2022, 02:03 AM
Last Post: snippsat
  string formatting barryjo 7 3,614 Jan-02-2022, 02:08 AM
Last Post: snippsat
  Help with string formatting in classes brthurr 6 14,212 Dec-17-2021, 04:35 PM
Last Post: Jeff900
  loop for dynamic cut string - cleaner way? korenron 4 2,887 Nov-22-2021, 02:30 PM
Last Post: korenron
  cursor.execute: How to insert dynamic number in a string? stoeberhai 2 5,012 Mar-18-2021, 12:55 PM
Last Post: stoeberhai
  Question on HTML formatting with set string in message Cknutson575 3 4,899 Mar-09-2021, 08:11 AM
Last Post: Cknutson575
  smtplib: string formatting not carrying over to email ClassicalSoul 1 3,616 Apr-22-2020, 09:58 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

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