I'm an absolute beginner trying to learn string validation. I have a variable about to store user input:
Text_input = raw_input('Type anything: ')
I want to check if Text_input contains at least one alphanumeric character. (If not, the program should print a message such as "Try again!" and ask the user to type again.) So, typing "A#" should pass but "#" should not. Any suggestions?
This worked for me:
Text_input = raw_input('Type anything: ')
if any(char.isalpha() or char.isdigit() for char in Text_input):
print "Input contains at least one alphanumeric character."
else:
print "Input must contain at least one alphanumeric character."
Related
Not sure how to accomplish what I want:
I am first asking the user to input a letter ranging from A to H. Once I grab that input, I want do STUFF if the input was valid, but I'm not sure how to verify that the input was valid.
while True:
input= raw_input("Enter letter between A-H: ")
if input "BETWEEN A-H": # (this is where I'm stuck)
# DO STUFF
break
else:
print "Invalid input. Try again"
continue
You can get the Unicode value of the character (with ord(character)) and check if it is in the desired range.
I've been working on a project and I've to check if the strings entered by user are alphanumeric or not.
For now, I've built my code and there's one function which needs to check if any word is alphanumeric or not.
The program is to let user enter a sentence along with his license number which would be alphanumeric like '221XBCS'. So, if the user enter suppose- 'My license number is 221124521' instead of 221XBCS I want the program to stop.
But my current program is assuming the re.match condition is true always. WHY IS IT SO??
import re
s = input("Please enter here:")
if re.search(r'\bnumber \b',s):
x = (s.split('number ')[1])
y = x.split()
z = y[0]
print(z)
if re.match('^[\w-]+$', z):
print('true')
else:
print('False')
The output looks like this for now:
Please enter here:my license number is 221
is
true
I want my program to grab alnum value from the input. That's all!
I think I understood your condition: the user should enter his license number which should contain only alphabetic characters AND numbers (both):
With built-in functions:
s = input("Please enter here:")
l_numbers = list(filter(lambda w: not w.isdigit() and not w.isalpha() and w.isalnum(), s.strip().split()))
l_number = l_numbers[0] if l_numbers else ''
print(l_number)
Let's say the user entered My license number is 221XBCS thanks.
The output will be:
221XBCS
With regular expressions, it is often valuable to look at the problem the reverse way.
It is, in this case, better to look if the string is NOT a pure numerical than looking if it IS an alphanumerical.
if re.match('[^\d]', z):
print('The string is no a pure numerical')
I'm pretty new to programming in python, so this is giving me problems. I'm searching for a way to uppercase a letter of a user's choosing in a word of user's choosing. For example, user writes staircase and as character he writes a and the end result would be stAircAse.
I know the code to ask user a question
promt='enter word:\n'
originalString=raw_input(promt)
promt='enter a character:\n'
upperCharacter=raw_input(promt)
But other then that I'm lost and would appreciate help.
i tried this code, but its not the user input of a letter to upper case
def chartoupper(instring,inchar):
indexes=[3,7]
chars=list(originalString)
for i in indexes:
chars[i]=chars[i].upper()
string=''.join(chars)
return string
promt='enter word:\n'
originalString=raw_input(promt)
promt='enter a character:\n'
upperCharacter=raw_input(promt)
newstring=chartoupper(originaString,upperCharacter)
print originaString
print upperCharacter
print newstring
print inchar
Try this -
if(len(upperCharacter) == 1):
finalString = originalString.replace(upperCharacter, upperCharacter.upper())
print finalString
As you should check if the user has indeed just added a single character, we added the if condition.
We are replacing all the occurrences of the character upperCharacter in originalString and assigning it to finalString. Refer the docs for this method
Answer for edited question --
def chartoupper(instring, inchar):
string = instring.replace(inchar, inchar.upper())
return string
promt='enter word:\n'
originalString=raw_input(promt)
promt='enter a character (note that only the 1st character will be used):\n'
upperCharacter=raw_input(promt)[0]
newstring=chartoupper(originalString, upperCharacter)
print originalString
print upperCharacter
print newstring
I have std strings like these:
UserName: Message
At first look it seems like an easy problem, but this issue is in that the name's last character could be a ':' and the first letter of the message part of the string could be a ':' too. The user could also have spaces in their name.
So A user might be names 'some name: '
and might type a message ' : Hello'
Which would look like:
'some name: : : Hello'
I do have the list (vector) of usernames though.
Given this, is there a way I could extract the username from this sort of string? (Ideally without having to iterate through the list of users)
Thanks
Try a regex like (\w+?):\ \w+.
If you can't gaurentee that the username won't contain a ":" characters, and you want to avoid iterating the entire list each time to check, you could try a shortcut.
Keep a vector of just the usernames that contain special chars (I'm imagining that this is a small subset of all usernames). Check those first, if you find a match, take the string after [username]: . Otherwise, you can simply do a naive split on the colon.
I would use string tokens
string text = "token, test string";
char_separator<char> sep(":");
tokenizer< char_separator<char> > tokens(text, sep);
BOOST_FOREACH(string t, tokens)
{
cout << t << "." << endl;
}
The way I would approach this is to simply find the first colon. Split the string there, and then trim the two remaining strings.
It's not entirely clear to me why there are additional colons and if they are part of the value. If they need to be removed, then you'll also need to strip them out.
I'm trying to find a regex that works to match a string of escape characters (an Expect response, see this question) and a six digit number (with alpha-numeric first character).
Here's the whole string I need to identify:
\r\n\u001b[1;14HX76196
Ultimately I need to extract the string:
X76196
Here's what I have already:
interact {
#...
#...
#this expression does not identify the screen location
#I need to find "\r\n\u001b[1;14H" AND "([a-zA-Z0-9]{1})[0-9]{5}$"
#This regex was what I was using before.
-nobuffer -re {^([a-zA-Z0-9]{1})?[0-9]{5}$} {
set number $interact_out(0,string)
}
I need to identify the escape characters to to verify that it is a field in that screen region. So I need a regex that includes that first portion, but the backslashes are confusing me...
Also once I have the full string in the $number variable, how do I isolate just the number in another variable in Tcl?
If you just want the number at the end, then this should be enough...
[0-9]{6}
Update with new information
Assuming \n is a newline character, rather than a literal \ followed by a literal n, you can do this...
\r\n\u001B\[1;14H(X[0-9]{5})
I found out a few things with some more digging. First of all I wasn't looking at the output of the program but the input of the user. I needed to add the "-o" flag to look at the program output. I also shortened the regex to just the necessary part.
The regex example from #rikh led me to look at why his or my own regex was failing, and that was due to the fact that I wasn't looking at the output but the input. So the original regex that I tried wasn't at fault but the data being looked at (missing the "-o" flag)
Here's the complete answer to my problem.
interact {
#...
-o -nobuffer -re {(\[1;14H[a-zA-Z0-9]{1})[0-9]{5}} {
#get number in place
set numraw $interact_out(0,string)
#get just number out
set num [string range $numraw 6 11]
#switch to lowercase
set num [string tolower $num]
send_user " stored number: $num"
}
}
I'm a noob with Expect and Tcl so if any of this doesn't make sense or if you have any more insights into the interact flags, please set me straight.