Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

Python - Flipping Binary 1's and 0's in a String

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> ''.join('1' if x == '0' else '0' for x in '1000110')
'0111001'

The a for b in c pattern is a generator expression, which produces a series of items based on a different series. In this case, the original series is the characters (since you can iterate over strings in Python, which gives you the characters that make up that string), and the new series is a set of characters with the 0's and 1's flipped.

'1' if x == '0' else '0' is pretty straightforward - it gives us whichever of 1 or 0 isn't x. We do this for each such x in the original set of characters, and then join() them all together (with an empty string '', a.k.a. nothing, in between each item), thus giving us a final string which is all of the opposite characters from the original, combined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...