7

I'm writing a program that will take a string as an input and check if the elements in it are valid or not. I want my input to only contain lower characters and periods, exclamation marks, and space and not an empty string. If the user enter an empty string or invalid character they will be asked to re-enter the string again:

I know how to check for a character in a string. I use this method

alpha ="abcdefghijklmnopqrstuvwxyz"
message= input("Enter message: ")
for i in message:
   if i in alpha:
      print i

Usually I will use the method below to check for invalid input, but it will not work for this case if I want to check for a character in a string. I can only use this to check if the message is empty

textOK = False
while not textOK:
        message= input(prompt)
        if len(message) == 0:
          print("Message is empty)
        else:
          textOK= True

This will re prompt the user whenever they input an empty string. I have no idea how to combine the two method. In short, I want to check if my input only contains lower letters,periods, exclamation marks, and space. If it contains other special characters or numbers or is an empty string, user will be prompt to enter the message again. Please help!!

martineau
  • 119,623
  • 25
  • 170
  • 301
K.U
  • 293
  • 1
  • 4
  • 15

4 Answers4

6

You can use a set of allowed chars checking if the set is a superset of the string entered:

allowed = set("abcdefghijklmnopqrstuvwxyz! .")

while True:
    message = input("Enter message: ")

    if message and allowed.issuperset(message):
        # do whatever
        break
    print("Invalid characters entered!")

It will only allow what is in allowed:

In [19]: message = "foobar!!$ "

In [20]:  message and allowed.issuperset(message)
Out[20]: False

In [21]: message = "foobar!! "

In [22]:  message and allowed.issuperset(message)
Out[22]: True

In [23]: message = ""

In [24]: bool( message and allowed.issuperset(message))
Out[24]: False

You can also use all()...:

while True:
    message = input("Enter message: ")
    if message and all(ch in allowed for ch in message):
        print("ok")
        break
    print("Invalid characters entered!)

If you want to output the bad chars:

while True:
    message = input("Enter message: ")
    if message and all(ch in allowed for ch in message):
        print("ok")
        break
    print("The following invalid character(s) were entered! {}"
          .format(" ".join(set(message)- allowed)))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2
import re
while True:
    txt = input('Enter message: ').strip()
    if re.match(r'^[a-z\. !]+$', txt):
        break

    print('Mistakes:', re.findall(r'[^a-z\. !]', txt))

print('correct!')
Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71
  • remove **.strip()** if you accept only spaces as well – Szabolcs Dombi Jul 10 '16 at 15:02
  • I know it sounds stupid but I trying to detect for special characters other than "abcdefghijklmnopqrstuvwxyz! .".. This will only check for valid character. Is there a way that I can check for invalid character, for example can I use if not re.match – K.U Jul 10 '16 at 15:17
  • invert regex: [^a-z\. !] please note that i removed ^ and $ and + – Szabolcs Dombi Jul 10 '16 at 15:21
1

Give a look at string.punctuation python function. You can also set which inputs are allowed/not allowed.

lucidBug
  • 197
  • 1
  • 10
1

a more advanced regex that only allows correct sentences:

import re
while True:
    txt = input('Enter message: ').strip()
    if re.match(r'^[a-z]+[\.\!]?([ ][a-z]+[\.\!]?)*$', txt):
        break

will allow:

ipsum. asd.
dolor sit amet consectetur adipiscing elit!
aenean libero risus consequat ac felis eget
aenean facilisis tortor nunc et sollicitudin
ut augue mauris tincidunt ut felis id mattis
fusce vel diam nec tellus consequat lacinia

will not allow:

two  spaces
hey!!
no!.
!me
! ! !
Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71