How can I customise error messages shown by PyInputPlus? - python

How can I customise error messages shown by PyInputPlus in python?
I have tried many method but unable to do it.
import pyinputplus as pyip
number = pyip.inputNum("Enter your phone number : ",
min=1000000000,
max=9999999999)
number
I want to print error message as please enter a valid 10 digit phone number.
Is there any way to so it?
I try to use "allowRegexes and blockRegexes" but unable to understand it.

If you are using this for a real world project I would recommend using input from python itself, this lib doesn't seem very well documented and mantained. This could bring a lot of weird errors in your code for the future.
But to answer your question, you could do it using regex with the parameter blockRegexes. If you were unable to understand it, this will be more a regex question than a python question.
From this website you can learn a lot about regex, that I recommend, regex is a very important tool to understand.
About your problem, accordingly to the docs:
blocklistRegexes (Sequence, None): A sequence of regex str or
(regex_str, error_msg_str) tuples that, if matched, will
explicitly fail validation.
So, in your case the first item in the tuple, should be a regex to block everything that have more or less than 10 integers characters:
^\d{10}$
The full explanation for this regex can be found here
The second item in your touple should be the string you want to appear when the error occurs:
"please enter a valid 10 digit phone number"
So your code would be like this:
number = pyip.inputNum("Enter your phone number : ",
min=1000000000,
max=9999999999,
blockRegexes=[(r"^\d{10}$","please enter a valid 10 digit phone number")])

Related

How to separate user's input with two separators? And controlling the users input

I want to separate the users input using two different separators which are ":" and ";"
Like the user should input 4 subject and it's amounts. The format should be:
(Subject:amount;Subject:amount;Subject:amount;Subject:amount)
If the input is wrong it should print "Invalid Input "
Here's my code but I can only used one separator and how can I control the users input?
B = input("Enter 4 subjects and amount separated by (;) like Math:90;Science:80:").split(";")
Please help. I can't figure it out.
If you are fine with using regular expressions in python you could use the following code:
import re
output_list = re.split("[;:]", input_string)
Where inside the square brackets you include all the characters (also known as delimiters) that you want to split by, just make sure to keep the quotes around the square brackets as that makes a regex string (what we are using to tell the computer what to split)
Further reading on regex can be found here if you feel like it: https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285
However, if you want to do it without importing anything you could do this, which is another possible solution (and I would recommend against, but it gets the job done well):
input_string = input_string.replace(";", ":")
output_list = input_string.split(":")
Which works by first replacing all of the semicolons in the input string with colons (it could also work the other way around) and then splitting by the remaining character (in this case the colons)
Hope this helped, as it is my first answer on Stack overflow.

How do I use regex correctly to correctly identify a command from a client to server in an internet relay chat program in python

So I was having a bit of trouble wording my question, but essentially I am working on a client application making commands to a IRC chat server that provide certain functionality. It was suggested we use regex to do the parsing of such commands. The first command that needs to be completed when a client is accepted by the server is the USER command which in general will look something like this:
"USER guest 0 * :Ronnie Reagan"
The parts are the USER, followed by the username which is 1 word and I believe can contain numbers, the mode which is a numeric value from 0-9 that indicates your current mode in the chat, the star is just unused extra stuff but it has to be there, and the last part is a colon with no space before the real name. Just as a note the manual doesn't say the real name has to be two separate names, just that it can contain spaces, so it can be any combination of letters and spaces even though its kind of weird.
This is what I came up with based on what I read about regex but have had some issues testing it.
"USER\s[a-zA-Z0-9]\s\d\s*\s:[a-zA-z\s]"
Here is the simple program I was using to test it based on some light tutorials I looked through
import re
userPattern = re.compile("USER\s[a-zA-Z0-9]\s\d\s*\s:[a-zA-z\s]")
while True:
regexTest = input()
isMatch = userPattern.match(regexTest)
if bool(isMatch) == True:
print("valid request")
else:
print("invalid request")
No matter the case I always get an invalid request and I've tried it in a few other ways too. I can't tell if its because something is wrong with my regex or my method of testing it.
There are some issues in your regex:
[a-zA-Z0-9] represents a single character, you want a plus sign at the end of it so that it matches 1 or more characters: [a-zA-Z0-9]+. Same thing about [a-zA-z\s].
* in regex is a special symbol, you need to escape it if you want to match an asterisk: \*
So this is the fixed version of your regex that should work:
USER\s[a-zA-Z0-9]+\s\d\s\*\s:[a-zA-z\s]+
But I think it could be simplified:
If you don't care about what goes after a colon then you can just use .+ there
Instead of [a-zA-Z0-9] you can just use \w (word matcher)
So I think this would work as well:
USER\s\w+\s\d\s\*\s:.+

How to search for symbols using regex

Learning Python and trying to get the User ID from a HTML page, through the use of Regular Expressions. (LTT is the website, just for practice).
I want to be able to type 'findID username' into cmd and return the 6 digit ID number.
Have spent hours trying different code and looking up references, maybe someone can explain it simple for me. I can configure the searchRegex object to correctly identify 6 digit numbers in the page, but it does not find the correct 6 digit combination that I am looking for. (Grabs another random 6 digits as opposed to the 6 specific User ID digits)
import re, requests, sys, time
if len(sys.argv)>1:
search=requests.get('https://linustechtips.com/main/search/?&q='+str(sys.argv[1:])+'&type=core_members')
searchRegex=re.compile(r"^'$\d\d\d\d\d\d^'$")
ID=searchRegex.search(search.text)
print(ID)
time.sleep(10)
else:
print('Enter a search term...')
I have tried many different ways of getting the code to recognise ' symbol. But when i try like this, returns None. Why can the regex find 6 digits, but can't find 6 digits beginning and ending with '.
This is the HTML page I am testing it on.
view-source:https://linustechtips.com/main/search/?&q=missiontomine&type=core_members
Try Regex: (?<=profile\/)\d{6}
Demo
The html text has the userid as part of the url like:
https://linustechtips.com/main/profile/600895-missiontomine/?do=hovercard
(?<=profile\/) does a positive lookbehind

Python3 NZEC Error

This piece of code is supposed to find account balance after withdraw from bank(fee=0.5).
wd,ac=raw_input().split(" ")
wd=int(wd)
ac=float(ac)
if(ac<wd):
print(ac)
elif(wd%5==0):
if(ac>wd+0.50):
print(ac-wd-0.50)
else:
print(ac)
else:
print(ac)
I got a Runtime NZEC Error while submitting on codechef. I am newbie and had searched for resolve and had used split(" ") in place of int(input()), which I had tried previously, but the problem still occurs.
Geeksforgeeks says:
"In python, generally multiple inputs are separated by commas and we read them using input() or int(input()), but most of the online coding platforms while testing gives input separated by space and in those cases int(input()) is not able to read the input properly and shows error like NZEC"
Given that I've tried to account for that... What is wrong with my code?
It looks like an error with your raw_input statement. Remember that, in python 3, raw_input doesn't exist any more. If you changed it from raw_input to input, then the code works just fine.

Python "SyntaxError: invalid token" on numbers starting with 0 (zeroes)

I know someone might think this question has been answered here but it doesn't have answer to what I want to achieve.
I have list of phone numbers, a very large one, and a whole lot of them starts with 08 and there is a lot of duplication, which is what I am trying to remove. Now I need to put them in a list or set so that I can use them in my program but it returns Invalid token as shown in the picture below:
Python assumes anything that starts with 0 as octal. How do I device a mean to bypass this and have these numbers in a list and then in a set?
read your phone input file, save each phone as string to a set, then the duplicates will be removed due to set only hold unique elements, and you can do further work on them.
def get_unique_phones_set():
phones_set = set()
with open("/path/to/your/duplicated_phone_file", "r") as inputs:
for phone in inputs:
# phone is read as a string
phones_set.add(phone.strip())
return phones_set
If you need to have them prepended by 08, use strings instead of ints.
a = ["08123","08234","08123"]
a = list(set(a)) # will now be ["08123","08234"]
Since (as you say) you don't have an easy way of surrounding the numerous numbers with quotes, go to http://www.regexr.com/ and enter the following:
Expression: ([0-9]+)
Text: Your numbers
Substitution (expandable pane at the bottom of the screen: "$&"

Categories