有没有一种方法可以使用for循环从索引中删除特定的字符串?

时间:2019-08-17 11:48:13

标签: python python-3.x

为了更好地理解,我正在尝试重新构建bin(x)的内置函数,这部分我已经讲完了,现在的问题是如何在不需要时动态删除0。

我尝试使用replace(),但是似乎要删除每个建议的“ 0”,我不确定如何选择零,直到它碰到第一个有“ 1”的索引为止 例如:

if i have 0b00010010
            ___
          0b00010010
               ^

我想选择0b后面的数字并立即删除0直到“ 1”

def bin(x):
    if x>0:
        binary = ""
        i = 0
        while x>0 and i<=16:
            string = str(int(x%2))
            binary = binary+string
            x/=2
            i = i+1
            d = binary[::-1]
            ret = f"0b{d}"
        return ret.replace("00","")
    else:
        x = abs(x)
        binary = ""
        i = 0
        while x > 0 and i <=16:
            string = str(int(x % 2))
            binary = binary + string
            x /= 2
            i = i + 1
            nd = binary[::-1]
            ret = f"-0b{nd}"
        return ret.replace("00","")

print(bin(8314))# 0b00010000001111010 this is the current out

0b00010000001111010这是当前输出

0b10000001111010这就是我想要的

3 个答案:

答案 0 :(得分:2)

最好不首先生成那些多余的零来简化事情:

redis-cli ping

打印

def bin(x):
    prefix = ("-" if x < 0 else "")
    x = abs(x)
    bits = []
    while x:
        x, bit = divmod(x, 2)  # division and remainder in one operation
        bits.append(str(bit))
    # Flip the bits so the LSB is on the right, then join as string
    bit_string = ''.join(bits[::-1])
    # Form the final string
    return f"{prefix}0b{bit_string}"

print(bin(8314))

答案 1 :(得分:2)

您应该看看lstrip()

date = getDobFromUser();
dob = DateTime(date.year, date.month, date.day);

当然,请确保在调用>>> b = "00010000001111010" >>> b.lstrip("0") '10000001111010' 之后后,在二进制文件前加上"0b"前缀。

答案 2 :(得分:1)

Scott Hunter为您的问题提供了一个很好的解决方案,但是,如果要使用for循环,请考虑尝试以下操作:

binary = "0b00010000001111010"
start_index = binary.find("b")
for index in range(b+1, len(binary)):
    if binary[index] == 0:
        binary = binary[0:index:] + binary[index+1::]
    else:
        break