在一行Python 3中打印循环输出

时间:2015-02-08 00:22:31

标签: python python-3.x printing line

我这里的代码将ASCII转换为Base 64,输入“Cat”给我输出 Base 64是Q. Base 64是2 Base 64是F. Base 64为0

如何在一行上打印输出,因此“Cat”会给出“Base 64是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))

1 个答案:

答案 0 :(得分:1)

首先在列表中收集base64个字符,然后在循环完成后加入它们并打印您的简介一次:

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)

这是更有效的方法;另一种较慢的方法是使用字符串连接,将base64字符添加到字符串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)