Dynamic Formatting of String - 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: Dynamic Formatting of String (/thread-8573.html) |
Dynamic Formatting of String - mikera1979 - Feb-26-2018 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. bit_size= '618' print('{} {}/{}'.format(*bit_size)) RE: Dynamic Formatting of String - Larz60+ - Feb-27-2018 use double slash in print statement. You need to escape the '/' which is itself an escape character RE: Dynamic Formatting of String - mikera1979 - Feb-27-2018 (Feb-27-2018, 04:06 AM)Larz60+ Wrote: use double slash in print statement. 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? 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)) |