0

How do I check if a string contains one substring variant like "all 3 digits numbers starting with 4 or 5"?

In my specific case, I want to check if an HTTP response header contains a 4xx or 5xx code.

Regex seems seems like overkill.

J. Doe
  • 1
  • 1
    `s[0] in '45' and s[1:3].isdigit()` maybe? But at that point the regex is probably more readable `r'[45]\d\d'` – anthony sottile Mar 07 '19 at 00:42
  • I am using requests library. The response text doesn't start with the code, so I can't check s[0]. – J. Doe Mar 07 '19 at 00:46
  • is the response [`r.status_code`](http://docs.python-requests.org/en/master/user/quickstart/#response-status-codes) available to you? – chickity china chinese chicken Mar 07 '19 at 00:52
  • @davedwards: it seems promising. I will give it a try. But the question still stands. – J. Doe Mar 07 '19 at 00:58
  • https://stackoverflow.com/questions/15258728/requests-how-to-tell-if-youre-getting-a-404 – s3n0 Mar 07 '19 at 01:00
  • @J.Doe in that case, `400 <= r.status_code <= 599` – anthony sottile Mar 07 '19 at 01:05
  • @davedwards: actually, I now have read more carefully the link you sent and it says I can raise an exception if a bad request is made. But in my case, I am looking for bad requests (it's a link checker script), so treating it as an exception doesn't seem appropriate. – J. Doe Mar 07 '19 at 01:08
  • @AnthonySottile: very elegant, but s3n0's link nailed it. In requests, I can check r.ok. Thanks guys! – J. Doe Mar 07 '19 at 01:14

0 Answers0