Ned Batchelder @nedbat.com · Dec 1

You can write short powerful #Python expressions using its many tools. Are there other ways to check if a string contains only "0" or "1"?

53 likes 14 replies

?

Replies

Anceps · Dec 6

set(s).issubset('01') and set(s) <= set('01') are a bit shorter.

Kevin Trainor · Dec 5

These are all clever. Yet, I don’t find any of them very readable. The telltale sign is that you needed the comments above to describe what these code examples are doing.

T

@tw33tzr4kidz.bsky.social · Dec 1

max(input or "Z") == "1" and min(input or "Z") == "0" ?

T

@tw33tzr4kidz.bsky.social · Dec 1

Ned, thank you for inspiring me to learn Python at in-person Python meetups in Boston. Following so I can continue to learn from you!

@jfljp.bsky.social · Dec 4

I like the set comparison for its clarity.

Oliver Theunissen · Dec 2

»There should be one — and preferably only one — obvious way to do it.« 😃

@albertbrandl.bsky.social · Dec 2

True if ((ss:=sorted(s)) and ss[0] in "01" and ss[-1] in "01") else False Not particularly efficient, since the characters have to be sorted first, but I always wanted to use the walrus operator like this...

Trey Hunner · Dec 1

Just to state the obvious one: s == "0" or s == "1" Great example of "the one obvious way"problem. Which is it? 🤔

ax3man1ac · Dec 1

I was thinking of using int(s, 2) but from what I recall it will cater for a 0b prefix so wouldn't pass the criteria, requires a try/except block, but on the plus side it's likely to be a common case of what you actually want to do with a 0/1 only string...

🇫🇮🇺🇦🇪🇺🐶🍕🍺 · Dec 1

not any(filter(lambda x: x not in {'0', '1'}, s)) and all(map(lambda x: x in '01', s)) and not bool(int(''.join(filter(lambda x: x not in '', s or '0')), 2) < 0) 😝

Yahel Carmon · Dec 1

Does s in ["0", "1"] not qualify? Feels like I’m missing something.

Jouni Seppänen · Dec 1

all(97*c-c*c>2351 for c in s.encode())

Rodrigo Girão Serrão 🐍🚀 · Dec 1

How about s.count("0") + s.count("1") == len(s) not (set(s) - set("01")) _ = int(s, 2) # Errors on failure, so I'm not sure it qualifies

osantana · Dec 1

I would use something like `int(s, 2)` but it fails because it accepts signed integers (eg `-1`) 😕