Let's say I have a string, and I want to check a lot of conditions on this string. For example:
- It is of size x
- Has no white spaces
- The last letter is a numeric character
All of the conditions from 1-3 It can be done in a regular standard way in a function (if this and that etc')
But... How would I do that in one line in a good python style way?
4 Answers 4
You can use a simple if condition with any:
s='fdsfgsgsfds9'
if len(s)==7 and not any(c.isspace() for c in s) and s[-1].isdigit():
pass
3 Comments
if len(s) == 7 and not any(c.isspace() for c in s) and s[-1].isdigit(): somewhat easier to read, I think.any(),solution edited. :)It may be more complicated than it's worth, but you can check all of those conditions with a regular expression.
For example, if the size you wanted was 8 characters, you could use the following to check all three conditions:
if re.match(r'\S{7}\d$', text):
print 'all conditions match'
Comments
One way would be to use a regular expression (assuming an x of 10):
if re.match(r"\S{10}(?<=\d)$", mystring):
# Success!
5 Comments
"\\S{%d}(?<=\\d)$" % x (not sure if you can do this with raw string)re.match(r"\S{%d}(?<=\d)$" % x, mystring)Try something like
import re
def test(s):
return len(s)>=x and re.match("^\S*\d$", s)
This will test whether the string has length of at least x and that it is a sequence of non-space-characters followed by a digit character at the end.
\S{x-1}\d$, (replacing x-1 with the actual number)