How do I use PyInputPlus to restrict input length and it's allowed characters? I did some research and found this question, but this question doesn't have answer specifically for PyInputPlus. And I want to allow both 'a-z' and 'A-Z'.
Code so far:
import pyinputplus as pyip
import re
oneLetter = pyip.inputStr(prompt=':')
if not re.match("^[a-z]*$", oneLetter):
print ("Error! Only letters a-z allowed!")
if len(oneLetter)>1:
print('You can only type in 1 character')
else:
print(oneLetter)
Desired output:
:1
>Only letters a-z, A-Z allowed
:Bob
>Only 1 letter allowed
:B
>B
CodePudding user response:
You may try the code below to fix your issue. I would suggest getting more familiar with regular expressions.
import re
import pyinputplus as pyip
oneLetter = pyip.inputStr(prompt=':')
if len(oneLetter) > 1:
print("You can only type in 1 character")
elif not re.match("^[a-zA-Z]$", oneLetter):
print("Error! Only letters a-z allowed!")
else:
print(oneLetter)