Python ASCII到二进制到一元的解决方案打印空行

Python ASCII到二进制到一元的解决方案打印空行,python,python-3.x,binary,ascii,Python,Python 3.x,Binary,Ascii,基本上,对于这个实践问题,我必须将ASCII字符串输入转换为二进制,然后将其转换为一元,一系列0和空格 例如:“C'='1000011'='0000000'00” 不幸的是,当打印变量“answer”时,代码只打印一个空行,该变量应该是0s和空格字符串。我找不到任何错误,但两个编译器返回相同的空行 import sys import math import binascii # Auto-generated code below aims at helping you parse # the

基本上,对于这个实践问题,我必须将ASCII字符串输入转换为二进制,然后将其转换为一元,一系列0和空格

例如:“C'='1000011'='0000000'00”

不幸的是,当打印变量“answer”时,代码只打印一个空行,该变量应该是0s和空格字符串。我找不到任何错误,但两个编译器返回相同的空行

import sys
import math
import binascii

# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.

message = "C"#input()

# Function which transforms text into a byte
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

# Sets up a switch to determine which block and of what type it is in
switch = 2
answer = ""

# Transforms string message into string of bits
byte = text_to_bits(message)
byte = byte[1:8]

for bit in byte:
    if bit == 1 and switch == 2:
        switch = 1
        answer = answer + "0 0"            
    elif bit == 1 and switch == 1:
        answer = answer + "0"            
    elif bit == 1 and switch == 0:
        switch = 1
        answer = answer + " 0 0"
    elif bit == 0 and switch == 2:
        switch = 0
        answer = answer + "00 0"
    elif bit == 0 and switch == 1:
        switch = 0
        answer = answer + " 00 0"        
    elif bit == 0 and switch == 0:
        answer = answer + "0"                

# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)

print(answer)

位的值始终为
'0'
'1'
。它永远不等于
0
1
,因此级联
if
中的任何条件都不为真。将
0
1
更改为相应的字符串。

位的值始终为
'0'
'1'
。它永远不等于
0
1
,因此级联
if
中的任何条件都不为真。将
0
1
更改为相应的字符串。

您的比较运算符不正确,您需要执行以下操作:

if bit == "1" and switch == 2:
...

您的比较运算符不正确,您需要执行以下操作:

if bit == "1" and switch == 2:
...