how to separate values with spaces in for loop

Viewed 114

So I have this program that gives the binary values of the ascii values plus 1 of a user input string.

text = input()
bitString = ''
for ch in text:
    new = ord(ch) + 1

    decimal = new
    while decimal > 0:
        remainder = decimal % 2
        decimal = decimal // 2
        bitString = str(remainder) + bitString

print(bitString)

If the user inputs "abcde" the output will be

11001101100101110010011000111100010

How do I get the binary values to be separated by spaces, where the output would be

1100010 1100011 1100100 1100101 1100110

?

5 Answers

Very slight change in your code to add space:

text = input()
bitString = ''
for ch in text:
    new = ord(ch) + 1

    decimal = new
    while decimal > 0:
        remainder = decimal % 2
        decimal = decimal // 2
        bitString = str(remainder) + bitString

    bitString = " " + bitString

print(bitString)

Output:

1100010 1100011 1100100 1100101 1100110
input = 'abcde'
bitString = ''
for i in list(input):
    bitString =  bitString + bin(ord(i)+1)[2:] + ' '
print(bitString)

I hope you want to get this way.

Here is the solution:

text = input()
bitString = ''
for ch in text:
    new = ord(ch) + 1

    decimal = new
    while decimal > 0:
        remainder = decimal % 2
        decimal = decimal // 2
        bitString = str(remainder) + bitString
splitStr = [bitString[i:i+7] for i in range(0, len(bitString), 7)]
print(" ".join(splitStr[::-1]))

Result:

1100010 1100011 1100100 1100101 1100110

OR

text = input()
bitString = ''
for ch in text:
    new = ord(ch) + 1
    decimal = new
    while decimal > 0:
        remainder = decimal % 2
        decimal = decimal // 2
        bitString = str(remainder) + bitString
    bitString = " " + bitString

print(" ".join(bitString.split()[::-1]))

Result:

1100010 1100011 1100100 1100101 1100110

Try this:

revBitString = bitString[::-1]
print(' '.join([revBitString[i:i+7][::-1] for i in range(0,len(revBitString),7)]))

Try using space at the end like this

    remainder = decimal % 2
    decimal = decimal // 2
    bitString = str(remainder) + bitString + " "

This should solve

Related