I'm working on a program that converts numbers to binary and vice versa. When the user enters a binary string such as 1011110110 it's converted to decimal and printed. I also want to print out the users inputted string like 10 1111 0110.
I have tried
print("Binary \t=\t " + ' '.join(binaryString[i:i+4] for i in range(0, len(binaryString), 4)))
Which will print out as 1011 1101 10. I'm wanting the spaces to start at the end of the string working forward like 10 1111 0110.
You can use the module % operator to know how many "overflow" numbers you have, then partition the remainder every 4th:
def neat_print(s):
ls = len(s)
start = ls % 4
rv, s = s[:start], s[start:]
return ' '.join([rv] + [s[i:i+4] for i in range(0,ls-start,4)]).strip()
for k in ["1010101010"[:end] for end in range(2,10)]:
print(k, "->", neat_print(k))
Output:
10 -> 10
101 -> 101
1010 -> 1010
10101 -> 1 0101
101010 -> 10 1010
1010101 -> 101 0101
10101010 -> 1010 1010
101010101 -> 1 0101 0101
You could use a recursive approach:
def rGroup(S,size=4,sep=" "):
return S if len(S)<=size else rGroup(S[:-size],size,sep) + sep + S[-size:]
output:
rGroup('1010101010') # '10 1010 1010'
rGroup('12345678',3,',') # '12,345,678'
binaryString = "1011110110"
print("Binary \t=\t " + rGroup(binaryString)) # Binary = 10 1111 0110
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With