将字符串中的零替换为1并将1替换为零的更有效方法(例如“ 100001”至“ 011110”)

目前,我正在这样做,但是问题是我正在遍历数千个这样的字符串(它们都比下面给出的示例字符串长得多),并且当前方法需要很长时间才能完成:

    example_string = '1001011101010010101010100100000001111011010101'
    reversed = ''
    for c in example_string:
        if c == '1':
            reversed += '0'
        elif c == '0':
            reversed += '1'
    print(reversed)

评论
  • Haley
    Haley 回复
    example_string.translate(str.maketrans("01","10"))
    
  • siusto
    siusto 回复

    use a list instead of reserved. every time you do reserved += '0' reserved is copied into memory, which takes a long time. try this:

    reversed = []
    for c in example_string:
        if c == '1':
            reversed.append('0')
        elif c == '0':
            reversed.append('1')
    print(''.join(reversed))