Expecting a certain format - python

So i'm trying to write a code for a router terminal simulator. And I'm using raw_input to read from the keyboard.
The problem is that I want to do a specific action when the user writes a sequence that matches this pattern: "<1-100> permit", so in order to accomplish this I wrote an if of this type:
if input == "%d permit" %number:
print 'Do this'
I want the number to be a value in the range of 1-100. I created a list with the range(1,100) function but I don't know how to check this condition inside my if.
I solved the problem however with the use of split function and some other conditions, but I can't really get over this idea and I want to find a solution. Any help would be greatly appreciated.

if input == "%d permit" %number and number in range(1,101):
print 'Do this'

Use re.match(pattern, value):
import re
[...]
if re.match(r"(\d\d?|100) permit", input):
do_something()
And the variable input will override the built-in function input(), so change the name to something else.
EDIT: As you don't want to use RegExp, you can split the string, pass it to int and then see if it's in the range.
if 1 <= int(input.split(" ")[0]) <= 100:
do_something()

Related

Can you convert list component into a function?

Hello I'm trying an hackerrank problem : String Validators
I actually solved the question but i'm trying a different approach on it.
Such as:
list=['isalnum()','isalpha()','isdigit()','islower()','isupper()']
for l in list:
count =0
for i in range(len(s)+1):
a=i.l
if a==1:
count+=1
if count !=0:
print(False)
elif count >0:
print(True)
Is there any way that I can convert components inside the list as a function and use it?
In python you can actually make a list of function:
if you have your array looking like this:
list=[isalnum,isalpha, isdigit, islower, isupper]
if you type
list[0]()
the function isalnum will be executed, obviously if they take parameters you can also pass parameters
in case you want the members of your list to be like you wrote:
list=['isalnum()','isalpha()','isdigit()','islower()','isupper()']
you can use the function eval() even if i don't suggest it:
eval(list[0])
will evaluate the string as a line of code and execute the function isalnum()

print() prints only every second input

I'm new to python and I've been trying to make a little function to call upon when I need to filter an input from everything except regular letters.
I've used SO for parts of the code, but I can't seem to understand why does it only print on every second try.
Here's my code:
import re
i=1
def inputFilterText():
inputRaw = input('input: ')
inputFiltered = re.sub('[^a-zA-Z]+', '', inputRaw)
return inputFiltered
while i > 0:
inputFilterText()
print(inputFilterText())
And here's my output:
I'm not really sure what's going on, but I presume it's a logical error. I've only just started using Python so any help is appreciated.
PSThe 'while' is only there so it's easier to test, it can be omitted.
You are calling inputFilterText twice. Once within the print() and once before. This is causing the code to prompt for input twice before printing the second response.
The problem is that you make a call to the inputFilterText function twice. The first time the output is discarded. Causing input to be taken twice, but only showing a result once.
To fix it, remove the inputFilterText() line. An example of working code.
import re
i=1
def inputFilterText():
inputRaw = input("input: ")
inputFiltered = re.sub(""[^a-zA-Z]+, "", inputRaw)
return inputFiltered
while i > 0:
print(inputFilterText())
Also, in future please send code as raw text, rather than screenshots.
Might I suggest using a variable here, you're not doing anything with the first filter call (this is why it's asking the first time) and the second one you're only printing.
while True:
txt = inputFilterText()
#do some stuff if needed
print(txt)

Questions concerning using regex in python

I currently am reading in a string that starts with a number up to the next delimeter and testing if the string read in is a float. Now I have a few questions here as I believe my regex works I just think I am not using the proper method once it tries to do it.
my particular float will be in the format of
d+(.d+)?(E(+|-)?d+)?
r'(\d+(\.\d+)?([E][+|-]?\d+)?'
Above is the regular expression I'm using and it is correct for the specifications I have set up, but my issue is that I will be reading in bad values and I want to print an error that either prints the whole string as bad or prints the part that passed followed by an error with the incorrect part printing. When I try I get the error print
print "ERROR: %s" % m.groups()
TypeError: not all arguments converted during string formatting
I feel like I am missing something simple but I cannot figure out what.
So in summary I am trying to use the above regular expression to compare a read in number string to see if it is in the float form. If the whole string conforms I want to print it and if there is a bad part I want to print the whole string as an error or print the good part follow by printing the bad part out with an error message.
p = re.compile(r'(\d+)(\.\d+)?(([E][+-])?\d+)?')
def is_float(str):
m = p.match(str)
if m:
print (m.groups())
return True
I have provided the piece of code I am working with perhaps there is an error there
Some sample inputs are:
3#33 //should print 3 then an error with #33 printed
3.435E-10 // should print the whole thing
0.45654 //should print the whole thing
4E-2 //should print the whole thing
m.groups() is an array. NOT a string, m.groups(0) is the entire match, m.groups(1) is the 1st set of capturing brackets in your regex and so forth.
Try:
print(m.groups())
To see the different values at play
First thing
You're missing a closing bracket. It should be:
(\d+(\.\d+)?([E][+|-]?\d+)?)
Notice the one at the end after the final ?
I then tested it here:
https://regex101.com/r/jF1jX2/1 and it worked.
I have to say, I'd not bother with a regex at all. Given a string that is supposed to represent a float, I'd do
def is_float(str):
try:
f = float(str)
return True
except ValueError:
return False
(BTW if the next step was going to be to convert an acceptable str to float,
just put the try .. except inline, use f if no exception is thrown and do whatever is appropriate when the exception is caught )
Also there's a mistake in your regex, in that it doesn't handle a leading "-" for a negative number (or a "+" for a positive one). Try ... except handles anything that you can throw at Python, using Python's rules.

How to elegantly evaluate if user input has numbers only in it using an if statement in Python?

I feel like this should be obvious, I've done this before even as a beginner but I just can't seem to write it in any way that isn't a horror to look at and Google searches aren't turning up anything useful (because I have no idea how to word this as a search)
You can use str.isdigit():
myinput = input() # in Python 2.x use raw_input()
if myinput.isdigit():
...
You can use isdigit()
foo = 1
bar = "2ab3*#"
str(foo).isdigit() # True
str(bar).isdigit() # False
With using the try-except syntax, you do not have to modify your existing code for the case of non-numeric input.
try:
a=int(input) # or a=float(input) if decimals are allowed
# perform your calculation here with a
except ValueError:
print 'You did not enter a number'

setting "if" to make sure variable is a number and not a letter/symbol

How do I create an "if" statement to make sure the input variable is a number and not a letter?
radius = input ('What is the radius of the circle? ')
#need if statement here following the input above in case user
#presses a wrong key
Thanks for your help.
Assuming you're using python2.x: I think a better way to do this is to get the input as raw_input. Then you know it's a string:
r = raw_input("enter radius:") #raw_input always returns a string
The python3.x equivalent of the above statement is:
r = input("enter radius:") #input on python3.x always returns a string
Now, construct a float from that (or try to):
try:
radius = float(r)
except ValueError:
print "bad input"
Some further notes on python version compatibility
In python2.x, input(...) is equivalent to eval(raw_input(...)) which means that you never know what you're going to get returned from it -- You could even get a SyntaxError raised inside input!
Warning about using input on python2.x
As a side note, My proposed procedure makes your program safe from all sorts of attacks. Consider how bad a day it would be if a user put in:
__import__('os').remove('some/important/file')
instead of a number when prompted! If you're evaling that previous statement by using input on python2.x, or by using eval explicitly, you've just had some/important/file deleted. Oops.
Try this:
if isinstance(radius, (int, float)):
#do stuff
else:
raise TypeError #or whatever you wanna do

Categories

Resources