Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a Python string every nth character iterating backwards

Tags:

python

binary

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.

like image 328
Saph_1991 Avatar asked Jun 13 '26 04:06

Saph_1991


2 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
like image 92
Patrick Artner Avatar answered Jun 14 '26 19:06

Patrick Artner


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
like image 27
Alain T. Avatar answered Jun 14 '26 18:06

Alain T.