Reputation: 1811
Let's say I have a string, and I want to check a lot of conditions on this string. For example:
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?
Upvotes: 1
Views: 198
Reputation: 250931
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
Upvotes: 7
Reputation: 208455
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'
Upvotes: 5
Reputation: 336128
One way would be to use a regular expression (assuming an x
of 10):
if re.match(r"\S{10}(?<=\d)$", mystring):
# Success!
Upvotes: 4
Reputation: 20267
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.
Upvotes: 1