Splitting a Python string every nth character iterating backwards

Viewed 150

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.

4 Answers

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

Just add [::-1] in two places in your code:

' '.join(binaryString[::-1][i:i+4] for i in range(0, len(binaryString), 4))[::-1]

p.s [::-1] reverse the string, so you just reverse it, add spaces in your way and then reverse again to proper initial order.

You need to work out where to start your cursor to print out the correct number at the start

string_length = len(binaryString)

# Start position is the remainder when dividing by 4
start_pos = string_length % 4

output_items = []

# Get first item
if start_pos > 0:
 output_items.append(binaryString[0:start_pos])

# Go through the remainder of the string
for i in range(start_pos, string_length, 4):
 output_items.append(binaryString[i:i+4])

print("Binary \t=\t " + ' '.join(output_items))
Related