0

I Have the code here which converts ASCII to Base 64, inputting "Cat" gives me the output The Base 64 is Q The Base 64 is 2 The Base 64 is F The Base 64 is 0

How can I make the output print on one line thus that "Cat" will give "The Base 64 is Q2F0"?

b64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
number = 0
numchar = 0
code = 0

user_input = input("Input")

for char in user_input:
    numchar = numchar + 1
    if numchar == 1:
        number = ord(char)
    elif numchar > 1:
        number = ord(char) + (number << 8)

    if numchar == 3:
        i=3
        for i in (3,2,1,0):
            code = number  >> (6 * i )

#print(int(code))
            print("Yout base64 is "+ b64_table[int(code)])

            number = number - (code  << (6 * i))
3
  • You could append the pieces of the result to a string during the iteration and then output the final string at the end. Commented Feb 8, 2015 at 0:25
  • I really don't see why you don't use base64.encode. Commented Feb 8, 2015 at 0:31
  • 1
    @bconstanzo: I really don't see why people cannot try and learn how base64 works as they learn to code. Commented Feb 8, 2015 at 0:32

1 Answer 1

1

Collect your base64 characters in a list first, then join them after the loop has completed and print your intro just once:

result = []
for i in (3,2,1,0):
    code = number  >> (6 * i )
    result.append(b64_table[int(code)]))
    number = number - (code  << (6 * i))

result = ''.join(result)
print("Your base64 is", result)

This is the more efficient method; the alternative slower method would be to use string concatenation, adding your base64 characters to a string result:

result = ''
for i in (3,2,1,0):
    code = number  >> (6 * i )
    result += b64_table[int(code)])
    number = number - (code  << (6 * i))

print("Your base64 is", result)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.