简体   繁体   中英

printing for loop output in one line Python 3

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))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM