2013-10-01 55 views
1

我期待的結果是使用。加入(某物),但結果沒有加入

>>> message_to bits('') 
'' 
>>> message_to_bits('hello') 
'0110100001100101011011000110110001101111' 

但是我所得到的是空字符串和字符串,只有1和0的錯誤第一個字符:

def char_to_bits(char): 
    """char_to_bits(char) -> string 

    Convert the input ASCII character to an 8 bit string of 1s and 0s. 

    >>> char_to_bits('A') 
    '01000001' 
    """ 
    result = '' 
    char_num = ord(char) 
    for index in range(8): 
     result = get_bit(char_num, index) + result 
    return result 

def get_bit(int, position): 
    """get_bit(int, position) -> bit 

    Return the bit (as a character, '1' or '0') from a given position 
    in a given integer (interpreted in base 2). 

    The least significant bit is at position 0. The second-least significant 
    bit is at position 1, and so forth. 

    >>> for pos in range(8): 
    ...  print(b.get_bit(167, pos)) 
    ... 
    1 
    1 
    1 
    0 
    0 
    1 
    0 
    1 
    """ 
    if int & (1 << position): 
     return '1' 
    else: 
     return '0' 

def message_to_bits(message): 
    for char in message: 
     result="".join(str(bits.char_to_bits(char))) 
    return result 

回答

0

你想加入兩次:

def message_to_bits(message): 
    return "".join("".join(str(bits.char_to_bits(char))) for char in message) 

第一個連接是在一個字符中的位,第二個是針對字符在消息中。

+0

感謝隊友的工作! –

+0

但空字符串呢? –

+0

@hwanghyungchae:對於一個空的字符串輸入,'for message in message'生成器應該產生一個空的可迭代的,所以結果應該是空字符串,對不對?抱歉,我目前正在使用平板電腦,無法驗證結果。 –