I need to write func to check str.
If should fit next conditions:
1) str should starts with alphabet - ^[a-zA-Z]
2) str should contains alphabet, numbers, . and - ([\w]+*.-)
3) str should ends with alphabet or number - \w$
4) length of str should be from 10 to 50
def check_login(str):
flag = False
if match(r'^[a-zA-Z]([\w]*.-)\w${10, 50}', str):
flag = True
return flag
It returns False to all combinations.
I think, error in 2 condition. I know, that I can use [a-zA-Z0-9\.-]+, but it does not indicate a mandatory entry.
How can I fix that?
Use:
match(r'^[a-zA-Z][\w.-]{8,48}\w$', str)
If you don't want to match _:
match(r'^[a-zA-Z][a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$', str)
If you want at least one dit, one dash, one letter and one digit:
^[a-zA-Z](?=.*-)(?=.*\.)(?=.*[0-9])[a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$
Where (?=....) is a lookahead, a zero-length assertion, that makes sure we have its content in the string.
Straight-forward approach with re.search() function:
import re
def check_login(s):
return bool(re.search(r'^[a-zA-Z][a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$', s)
and re.search(r'\.[a-zA-Z0-9]*-|-[a-zA-Z0-9]*\.', s[1:-1]))
# test cases
print(check_login('al-De.5af3asd.2')) # True
print(check_login('3lDe.5af3asd.2')) # False
print(check_login('al-De.5a')) # False
print(check_login('xl-De.5a3333333333333')) # True
You can try this regex:
import re
final_string = [''] if not re.findall("^[a-zA-Z]{1}[a-zA-Z0-9\-\.]{9,49}\d$|\w$", s) else re.findall("^[a-zA-Z]{1}[a-zA-Z0-9\-\.]{9,49}\d$|\w$", s)
if final_string[0] == s:
#success, a match has been found.
pass
Related
I have a bunch of string look like aaa -bx or aaa -bxx where x would be a digit. Is there any way to mach bx or bxx without using regrex? I remember there is something like b_ to match it.
You can use string methods.
Matching literal aaa -b followed by digits:
def match(s):
start = 'aaa -b'
return s.startswith(start) and s[len(start):].isdigit()
match('aaa -b33')
# True
If you rather want to check if the part after the last b are digits, use s.rsplit('b')[-1].isdigit()
Well it is not eloquent, but you can certainly test the string 'bxx' where xx represents one or two digits, manually, in a manner of speaking.
Here is an example. First check if it has sufficient length and starts with 'b'. Then check whether the next part is an integer.
def matchfunction(s):
if len(s) < 2 or s[0] != 'b':
return False
try:
int(s[1:])
return True
except:
return False
print( matchfunction( 'b23' ) )
print( matchfunction( 'bavb' ) )
The output, as expected, is
True
False
I wasn't sure what to title it, but I'm writing a function that checks if a phrase is a palindrome or not. If something is capitalized or not doesn't matter and if there are other characters it will remove them. If the string is the same forwards and backwards (that's what a palindrome is) then it will be a Boolean True, and a Boolean False if it isn't. For example:
is_palindrome('ta.cocat')
#It would return
True
is_palidrome('Tacocat')
#It would return
True
is_palindrome('tacodog')
#It would return
False
I've written code that will take out extra characters, but I can't figure out how to make it that capitalization doesn't matter.
#Strip non-alpha
def to_alphanum(str):
return ''.join([char for char in str if char.isalnum()])
#Palindromes
def is_palindrome(str):
str = to_alphanum(str)
if(str==str[::-1]):
return True
else:
return False
#Here's examples about what it returns
is_palindrome('taco.cat')
True
is_palindrome('Tacocat')
>>> False
just use the lower function on your input string, so that case doesnt matters in your function
str = to_alphanum(str).lower()
You can simply use:
def isPalindrome(s):
s = to_alphanum(s).lower()
rev = s[::-1]
# Checking if both string are equal or not
if (s == rev):
return True
return False
s1 = "malayalam"
>>> isPalindrome(s1)
True
I need to write func to check str. If should fit next conditions:
1) str should starts with alphabet - ^[a-zA-Z]
2) str may contains alphabet, numbers, one . and one -
3) str should ends with alphabet or number
4) length of str should be from 1 to 50
def check_login(str):
flag = False
if match(r'^[a-zA-Z][a-zA-Z0-9.-]{1,50}[a-zA-Z0-9]$', str):
flag = True
return flag
But it should mean that it starts with alphabet, length of [a-zA-Z0-9.-] is more than 0 and less 51 and it ends with [a-zA-Z0-9].
How can I limit quantity of . and - and write length's limit to all expression?
I mean that a - should returns true, qwe123 also true.
How can I fix that?
You will need lookaheads:
^ # start of string
(?=^[^.]*\.?[^.]*$) # not a dot, 0+ times, a dot eventually, not a dot
(?=^[^-]*-?[^-]*$) # same with dash
(?=.*[A-Za-z0-9]$) # [A-Za-z0-9] in the end
[A-Za-z][-.A-Za-z0-9]{,49}
$
See a demo on regex101.com.
Which in Python might be:
import re
rx = re.compile(r'''
^ # start of string
(?=^[^.]*\.?[^.]*$) # not a dot, 0+ times, a dot eventually, not a dot
(?=^[^-]*-?[^-]*$) # same with dash
(?=.*[A-Za-z0-9]$) # [A-Za-z0-9] in the end
[A-Za-z][-.A-Za-z0-9]{,49}
$
''', re.VERBOSE)
strings = ['qwe123', 'qwe-123', 'qwe.123', 'qwe-.-123', '123-']
def check_login(string):
if rx.search(string):
return True
return False
for string in strings:
print("String: {}, Result: {}".format(string, check_login(string)))
This yields:
String: qwe123, Result: True
String: qwe-123, Result: True
String: qwe.123, Result: True
String: qwe-.-123, Result: False
String: 123-, Result: False
So a user will input a string value in binary format. i.e. '01000001'
I want to check the value they enter to see if it:
has only eight characters.
is a string type
and only contains '0's or '1's
preferably to be done with a function that takes in the user value so that i can call it whenever. Returns false if conditions are not met.
this is what i came up with so far...
size = len(teststring)
teststring = '11111111'
def typecheck(value):
if type(user_input) == type(teststring) and len(user_input) == size and contains only 1 | 0
return
You can use regex matching here:
reg = re.compile(r'^[01]{8}$')
def typecheck(value):
return isinstance(value, str) and bool(reg.match(value))
Or since you want to check for binary format number, how about converting it to int with base 2, and see if it's a valid conversion:
def typecheck(value):
try:
return len(value) == 8 and bool(int(value, 2))
except TypeError, ValueError:
return False
No need for regex
You could use str.strip() and strip all 1 and 0 from end and beginning and check.
Code:
check = "11101110"
if isinstance(check,str) and len(check)==8 and check.strip("01")=='':
print "yes"
Output:
yes
This can be done with one if statement. If the regex doesn't find a match it will return None which evaluates to False in a truth test.
import re
def check_input(user_input):
if not re.match(r'^[01]{8}$', user_input):
it doesn't meet requirements do something
This is my code. it seems to be checking only the first character. I'd like to know how to fix it.
import string
ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DECIMAL_DIGITS = "0123456789"
ALPHABETS = ASCII_LOWERCASE + ASCII_UPPERCASE
def is_alpha(string):
for c in "string":
if c in ALPHABETS:
return False
else:
return True
Do not return in every iteration, only return False when you find something that is not in ALPHABET. What about this?
def is_alpha(your_string):
for c in your_string:
if c not in ALPHABETS:
return False
return True
actually its almost half right:
def is_alpha(string):
for c in string:
if not c in ALPHABETS:
return False
return True
short circuiting on False is ok but you need to finish the loop to determine True
There's several issues with your code here.
In your function definition you say
for c in "string"
which means you're checking the characters in the string literal "string".
You'll need to remove the quotes to have it refer to your parameter and actually check the string you're looking at. Further, you should change the name of your parameter and variable to something less ambiguous than string.
As Two-Bit Alchemist points out, you're returning from inside the loop so if the first character is in ALPHABETS then it returns and doesn't execute any more.
Which goes to the final issue. You're returning False if it is an alpha character instead of true. If you change
if c in ALPHABETS:
return False
to
if c not in ALPHABETS:
return False
then delete the else branch and put the return True after the loop it will work as you intend.
Change your function like this:
def is_alpha(string):
for c in string:
if c not in ALPHABETS:
return False
return True
First of all, you had for c in "string": in your code. There you are creating a new string ("string") and looping through the characters in it. Instead, you want to loop through the parameter passed to your function. So remove the double quotes.
Your function returns after first character because you are returning in both cases. Return true only when all characters are in ALPHABETS