Python check if input variable matches format [duplicate] - python

This question already has answers here:
Checking whether a string starts with XXXX
(5 answers)
Closed 2 years ago.
I'm attempting to make a 'check' to see if a given link matches a certain pattern. Here's what I have so far:
love = input("Enter URL: ")
while True:
if love == 'https://www.youtube.com/watch?v=*':
print("confirm, what is love?")
break
else:
print("NOT A YOUTUBE LINK")
love is supposed to be a youtube link, starting in https://www.youtube.com/watch?v= and ending in 11 wildcard characters. How would one do this?

Use the startswith() method.
if love.startswith('https://www.youtube.com/watch?v='):

If you need exactly 11 characters after the =, you could use regex:
import re
love = input("Enter URL: ")
if re.search(r"http://youtube.com/watch\?v=.{11}", love):
print("Valid")
else:
print("Invalid")
The .{11} in the regex pattern means match any character (.) exactly 11 times ({11}).

You don't need a while loop for the if statement like that. If you write it that way, your program will continuously print out "NOT A YOUTUBE LINK" because you have no break for else. If you put a break in your else statement, then there is no use for a while loop, since you stop the program after one try anyway. Also, use startswith() to check for the URL
If you want to use a loop, you can use it this way:
def checkURL(inputURL):
if inputURL.startswith('https://www.youtube.com/watch?v='):
print("confirm, what is love?")
else:
print("NOT A YOUTUBE LINK")
while True:
love = input("Enter URL: ")
if love.lower() != "quit":
checkURL(love)
else:
break

I see some problems with your code:
you don't need the while loop, it will end your computer memory as long it is not a youtube link
You can just check if youtube.com in the string variable.
youtube domains can be **youtube.com`, youtu.be, and maybe some more that I don't know about. I suggest putting all of them in a list and check.

Related

How can I check if a string contains a special letter? [duplicate]

This question already has answers here:
How to check a string for specific characters?
(8 answers)
How to check a string for a special character?
(5 answers)
Closed 5 years ago.
I am building a program that gets a password as a string and checks its strength by a couple of factors. I want to check if the entered string contains a special character (like %,$,# etc.) but so far I couldn't able to figure it out. What is the best way to do so?
Edit: I am not searching for a specific character. I need to search the string to find if it has some kind of a non-letter, non-digit character.
Edit 2 : I want to do it without a loop.
You can possibly use regex!
>>> import re
>>> s='Hello123#'
>>> re.findall('[^A-Za-z0-9]',s)
['#']
>>> if re.findall('[^A-Za-z0-9]',s):print True
...
True
Happy Coding!
Hope it helps!
As you stated you don't want to use a loop, and probably never worked with regexes, how about a list comprehension?
import string
all_normal_characters = string.ascii_letters + string.digits
def is_special(character):
return character not in all_normal_characters
special_characters = [character for character in password if is_special(character)]
Let me know if this works, or if you need more help!
You will have to put his into a for loop to check for special character and I think you need to make a list with them all in and then test it like that but this is the basic code you need! Replace the print bit with whatever else you need to do!
password = "VerySecurePassw0rd"
if "%" in password:
print( "Your Password has a special character in it!")
if "%" not in password:
print ("Your Password does not have a special character in it!")
EDIT:
Or you could use "else" above
Without using a loop I'm not sure however you could use "elif" but it's not very efficient
password = "VerySecurePassw0rd"
if "%" in password:
print ("Your Password has a special character in it!")
elif "$" in password:
print( "Your Password has a special character in it!")
elif "#" in password:
print ("Your Password has a special character in it!")
You could also try this:
if "%" and "$" in password:
print("Your Password has a 2 special characters in it!")
I think that should work

Python not reading from list corretly

Okay, below is my issue:
this program reads from a file, makes a list without using rstrip('\n'), which I did on purpose. From there, it prints the list, sorts it, prints it again, saves the new, sorted list to a text file, and allows you to search the list for a value.
The problem I am having is this:
when I search for a name, no matter how I type it in, it tells me that its not in the list.
the code worked til I changed the way I was testing for the variable. Here is the search function:
def searchNames(nameList):
another = 'y'
while another.lower() == 'y':
search = input("What name are you looking for? (Use 'Lastname, Firstname', including comma: ")
if search in nameList:
print("The name was found at index", nameList.index(search), "in the list.")
another = input("Check another name? Y for yes, anything else for no: ")
else:
print("The name was not found in the list.")
another = input("Check another name? Y for yes, anything else for no: ")
For the full code, http://pastebin.com/PMskBtzJ
For the content of the text file: http://pastebin.com/dAhmnXfZ
Ideas? I feel like I should note that I have tried to add ( + '\n') to the search variable
You say you explicitly did not strip off the newlines.
So, your nameList is a list of strings like ['van Rossum, Guido\n', 'Python, Monty\n'].
But your search is the string returned by input, which will not have a newline. So it can't possibly match any of the strings in the list.
There are a few ways to fix this.
First, of course, you could strip the newlines in your list.
Alternatively, you could strip them on the fly during the search:
if search in (name.rstrip() for name in nameList):
Or you could even add them onto the search string:
if search+'\n' in nameList:
If you're doing lots of searches, I would do the stripping just once and keep a list of stripped names around.
As a side note, searching the list to find out if the name is in the list, and then searching it again to find the index, is a little silly. Just search it once:
try:
i = nameList.index(search)
except ValueError:
print("The name was not found in the list.")
else:
print("The name was found at index", i, "in the list.")
another = input("Check another name? Y for yes, anything else for no: ")
Reason for this error is that any input in your list ends with a "\n". SO for example "john, smith\n". Your search function than uses the input which does NOT include "\n".
You've not given us much to go on, but maybe using sys.stdin.readline() instead of input() would help? I don't believe 2.x input() is going to leave a newline on the end of your inputs, which would make the "in" operator never find a match. sys.stdin.readline() does leave the newline at the end.
Also 'string' in list_ is slow compared to 'string' in set_ - if you don't really need indices, you might use a set instead, particularly if your collection is large.

How can I check if the users input is a number?

I'm trying to create a function to check if the user inputs a number. If the user inputs a number my program should output an error message, if the users enters a string of letters, my program should proceed with program. How can I do this?
I've come up with this so far:
#Checks user input
def CheckInput():
while True:
try:
city=input("Enter name of city: ")
return city
except ValueError:
print ("letters only no numbers")
This function doesn't seem to work. Please help.
You are looking to filter out any responses that include digits in the string. The answers given will do that using a regular expression.
If that's all you want, job done. But you will also accept city names like Ad€×¢® or john#example.com.
Depending on how choosy you want to be, and whether you're just looking to fix this code snippet or to learn the technique that the answers gave you so that you can solve the next problem where you want to reject anything that is not a dollar amount, say),you could try writing a regular expression. This lets you define the characters that you want to match against. You could write a simple one to test if the input string contains a character that is not a letter [^a-zA-Z] (the ^ inside [ ] means any character that is not in the class listed). If that RE matches, you can then reject the string.
Then consider whether the strict rule of "letters only" is good enough? Have you replaced one flawed rule (no digits allowed) with another? What about 'L.A.' as a city name? Or 'Los Angeles'? Maybe you need to allow for spaces and periods. What about hyphens? Try [^a-zA-Z .-] which now includes a space, period and hyphen. The backslash tells the RE engine to treat that hyphen literally unlike the one in "a-z".
Details about writing a regex here:http://docs.python.org/3/howto/regex.html#regex-howto
Details about using the Re module in Python here: http://docs.python.org/3/library/re.html#module-re
import re
def CheckInput():
city = input('Enter name of city: ')
if re.search(r'\d', city):
raise Exception('Invalid input')
You wouldn't be type checking because in Python 3 all text inputs are strings. This checks for a decimal value in the input using regular expressions and raises an exception if one is found.
val = input("Enter name of city:")
try:
int( val )
except ValueError:
return val
else:
print("No numbers please")
Edit: I saw mention that no number should be present in the input at all. This version checks for numbers at any place in the input:
import re
val = input("Enter name of city:")
if re.search( r'\d', val ) is not None:
print("No numbers please")
else:
return val
You can use the type(variable_name) function to retrieve the type.

How to verify numbers in input with python?

I'm trying to learn how to program and I'm running into a problem....
I'm trying to figure out how to make sure someone inputs a number instead of a string. Some related answers I found were confusing and some of the code didn't work for me. I think someone posted the try: function, but it didn't work, so maybe I need to import a library?
Here's what I'm trying right now:
Code:
print "Hi there! Please enter a number :)"
numb = raw_input("> ")
if numb != str()
not_a_string = int(next)
else:
print "i said a number, not a string!!!"
if not_a_string > 1000:
print "You typed in a large number!"
else:
print "You typed in a smaller number!"
Also I have another question while I'm asking. How can I make it so it will accept both uppercase and lower case spellings? In my code below, if I were to type in "Go to the mall" but with a lowercase G it would not run the if statement because it only accepts the capital G.
print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep"
answer = raw_input("> ")
if answer == "Go to the mall":
print "Awesome! Let's go!"
elif answer == "Get lunch":
print "Great, let's eat!"
elif answer == "Go to sleep":
print "Time to nap!"
else:
print "Not what I had in mind...."
Thanks. ^^
Edit: I'm also using python 2.7 not 3.0
You can do something like this:
while True: #infinite loop
ipt = raw_input(' Enter a number: ')
try:
ipt = int(ipt)
break #got an integer -- break from this infinite loop.
except ValueError: #uh-oh, didn't get an integer, better try again.
print ("integers are numbers ... didn't you know? Try again ...")
To answer your second question, use the .lower() string method:
if answer.lower() == "this is a lower case string":
#do something
You can make your string comparisons really robust if you want to:
if answer.lower().split() == "this is a lower case string".split():
In this case, you'll even match strings like "ThIs IS A lower Case\tString". To get even more liberal in what you accept, you'd need to use a regular expression.
(and all this code will work just fine on python2.x or 3.x -- I usually enclose my print statements in parenthesis to make it work for either version).
EDIT
This code won't quite work on python3.x -- in python3, you need to change raw_input into input to make it work. (Sorry, forgot about that one).
First,you should ask only one question per post.
Q1: use built-in .isdigit()
if(numb.isdigit()):
#do the digit staff
Q2:you can use string.lower(s) to solve the capital issue.
you may try
numb = numb.strip()
if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit():
# process numb

Python program isn't displaying an output [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I determine if user input is a valid hexadecimal number?
Python - Program not displaying as intended
#Hex Check
def Check(HexInput):
while True:
if HexInput in Valid:
print('That is a valid hex number.')
else:
print('That is an invalid hex number.')
return HexInput
HexInput=input('Enter a hex number: ')
Valid='1234567890ABCDEFG'
Program needs to contain Check(). It should ask the user to input a hex number and tell them whether it's a valid hex number or not.
First of all,
while False:
will never execute. You can use "while True:" or "while checked == False:" but not "while False:"
Your Check() function must also take in parameters so that it looks like
def Check(UserInput, Valid):
You also need an additional "if" statement because even if the user inputs an invalid hex value, the program will still print "That is a valid hex value."
Next,
return Check
does not make sense as you do not have any variable named "Check"
Finally, you must actually call your function like so:
Check(UserInput, Valid)
It is not clear what you want to do in your program but for start , while False: mean that the code in the while loop will always be ignored (not executed)
The body of the while False: will never execute.
while False:
print("You will never enter this loop.")
.
.
.
This will execute, but you have to make sure you test for a condition,
so you can break out of the loop. That is you do not want to loop endlessly.
while True:
print("You will enter this loop.")
print("Make sure you test for a condition that will let you "break".)
break
Edit: You asked me to check your program. There are still some problems.
Use raw_input instead of input. The Python Tutorial at http://docs.python.org suggested raw_input.
The way you've written your program, if you have a multi-digit number, you'd need to check each digit, and that's what Python's for is for.
I've written something crude. In my version you'd test for 0 or non-zero. If
zero, you don't have a hex number. I'm sure there is a more elegant way to do this.
I strongly suggest fiddling with code in the Python command line. That's what it's for.
def Check(HexInput):
valid_hex_digit = 0 #Assume invalid
for digit in HexInput:
if digit in Valid:
valid_hex_digit = valid_hex_digit + 1
else:
error_str = "Invalid hex digit " + str(digit) + " found."
print(error_str)
valid_hex_digit = 0
break
return valid_hex_digit

Categories