Reputation: 21
I need a command in python which filters the letters in a string but not deleting them for example:
string =raw_input("Enter the string:")
if string.startswith("a") and string.endswith("aaa"):
print "String accepted"
else: print "String not accepted"
if "ba" in string:
print "String accepted"
else :
print "String is not accepted"
What should I add to ban other letters except a and b in the string
Upvotes: 2
Views: 441
Reputation: 5384
Try something like this. It lets you set multiple letters, symbols, etc
valid_char = ['a', 'b']
def validate(s):
for char in s:
if char not in valid_char:
return False
return True
if validate(input("Enter the string:")):
print('Sting Accepted')
else:
print('Sting not Accepted')
Upvotes: 0
Reputation: 90889
You can use a set , convert your string to a set and check if its a subset of a set with only a
and b
. Example -
s = raw_input("Enter the string:")
validset = set('ab')
if set(s).issubset(validset):
print "String accepted"
else:
print "String not accepted"
Demo -
>>> s = "abbba"
>>> validset = set(['a','b'])
>>> if set(s).issubset(validset):
... print "String accepted"
... else: print "String not accepted"
...
String accepted
>>> s = "abbbac"
>>> if set(s).issubset(validset):
... print "String accepted"
... else: print "String not accepted"
...
String not accepted
Or as indicated in the comments you can use set.issuperset()
instead . Example -
s = raw_input("Enter the string:")
validset = set('ab')
if validset.issuperset(s):
print "String accepted"
else:
print "String not accepted"
Upvotes: 1
Reputation: 10119
This is a good use of regular expressions:
import re
my_string = raw_input("Enter the string:")
if re.match('^[ab]+$', my_string):
print "String accepted"
else :
print "String is not accepted"
This will match strings which contain only the characters a
and b
, of non-zero length. If you want to match zero-length strings, use *
instead of +
.
Upvotes: 1
Reputation: 1625
You could use a regex to search for letters and combinations you want to filter.
^((?![abcd]).)*$
will match things that don't contain a
, b
, c
or d
.
Upvotes: 0
Reputation: 49318
You can simply replace them with the empty string and check whether there's anything left:
string = raw_input("Enter the string:")
if string.replace('a','').replace('b',''):
print "String not accepted"
else:
print "String accepted"
The original string string
will not be modified.
Upvotes: 2