Python - 翻转字符串中的二进制 1 和 0

问题描述:

我正在尝试取字符串形式的二进制数并翻转 1 和 0,即将字符串中的所有 1 更改为 0,并将所有 0 更改为 1.我是 Python 的新手,我已经绞尽脑汁几个小时试图弄清楚它.

I'm trying to take a binary number in string form and flip the 1's and 0's, that is, change all of the 1's in the string to 0's, and all of the 0's to 1's. I'm new to Python and have been racking my brain for several hours now trying to figure it out.

Amber 的回答虽然优秀,但可能不是最清楚的,所以这里是一个超级基本的迭代示例:

Amber's answer, while superior, possibly isn't the most clear, so here's a super basic iterative example:

b_string = "1100101"
ib_string = ""

for bit in b_string:
  if bit == "1":
    ib_string += "0"
  else:
    ib_string += "1"

print ib_string

这可以通过更好的方式来完成……替换、理解,但这是一个例子.

This can be done in much better ways...replacements, comprehensions, but this is an example.

一旦你理解了这个问题的基础,我就会从这个问题的其他答案中学习.这种方法缓慢而痛苦.为了最佳性能,正如Muhammad Alkaouri 指出的那样,string.translate/maketrans 组合是去.紧随其后的是领悟.我的代码是最慢的.

I would learn from the other answers in this question once you understand the basis of this one. This method is slow and painful. For the best performance, as Muhammad Alkarouri pointed out, the string.translate/maketrans combo is the way to go. Right behind it is the comprehension. My code is the slowest by a significant margin.