How to check a text contains \ - python

def check(text):
pattern = re.compile(r'\\')
rv = re.match(pattern, text)
if rv:
return True
else:
return False
print check('\mi') # True
print check('\ni') # False
Actually,I want text contains '\' is illegal.
But '\n', '\b',etc, python treats them specially,so I can not match them out.
Any solutions?

Why would you need or want to use a regex for this?
return '\\' in text

def check(text):
rv = re.search('(\\\\)|(\\\n)', string)
if rv:
return True
else:
return False
string = "\mi"
print check(string)
string = "\ni"
print check(string)
Result:
================================ RESTART ===============
True
True
\\\n includes newlines.
You can specifically search this way for \n by escaping \\ and adding \n. Works with \b etc...

Related

Exclude space from allowed input when entering float number

I've written a validation function that looks like this:
def validateFloat(self, text):
if (text == ''):
return True
try:
float(text)
return True
except ValueError:
return False
But I can still enter spaces after I enter a digit. I want to make it so that it doesn't allow spaces, only dots and digits.
Thanks in advance.
If you only want to catch spaces
def validateFloat(self, text):
if (text == ''):
return True
elif ' ' in text:
return False
try:
float(text)
return True
except ValueError:
return False
You can simply use
x=isinstance(text,float)
if text variable is float, this will return true.
To remove space from text use strip function as mentioned below.
text.strip()
If you want to check whitespace in text. Use below
if ' ' in text:

Print all in once

The code that I provided below prints the output one line at a time. However, I want to rewrite the code to print all the content all together at once.
def filters():
for LogLine in Log:
flag = True
for key,ConfLine in Conf.items():
for patterns in ConfLine:
print patterns
if re.match((DateString + patterns), LogLine):
flag = False
break
if(flag == False):
break
if(flag):
print LogLine
Thanks
Here's the general technique:
lines = []
for ...
lines.append(<whatever you were going to print>)
print '\n'.join(lines)
There is one thing that I would do. I would initialize an empty dictionary or empty list and then append all the items to the empty dictionary or empty list. Finally print the output all together at once.
def filters():
mypatterns=[]
for LogLine in Log:
flag = True
for key,ConfLine in Conf.items():
for patterns in ConfLine:
print patterns
mypatterns.append(patterns)
if re.match((DateString + patterns), LogLine):
flag = False
break
if(flag == False):
break
if(flag):
print LogLine
print mypatterns

String manipulating in python

I'm trying to make a function that will take a string an remove any blocks of text from it. For example turning "(example) somestuff" into "somestuff" removing any blocked text from the string. This is a single function for a large program that is meant to automatically create directories based on the files name and move relevant files into said folder. I think I'm running into an endless loop but lost as to what by problem is.
startbrackets = '[', '('
endbrackets = ']', ')'
digits = range(0,10)
def striptoname(string):
startNum = 0
endNum = 0
finished = True
indexBeginList = []
indexEndList = []
while (finished):
try:
for bracket in startbrackets:
indexBeginList.append(string.find(bracket, 0, len(string)))
except:
print "Search Start Bracket Failed"
wait()
exit()
# Testing Code START
finished = False
for i in indexBeginList:
if i != -1:
finished = True
startNum = i
break
# Testing Code END
try:
for bracket in endbrackets:
indexEndList.append(string.find(bracket, 0, len(string)))
except:
print "Search End Bracket Failed"
wait()
exit()
# Testing Code START
for i in indexEndList:
if i != -1:
endNum = i
break
# Testing Code END
if(finished):
if(startNum == 0):
string = string[:(endNum+1)]
else:
string = string[0:startNum]
for i in digits:
string.replace(str(i),"")
return string
Here's an approach using re:
import re
def remove_unwanted(s):
# This will look for a group of any characters inside () or [] and substitute an empty string, "", instead of that entire group.
# The final strip is to eliminate any other empty spaces that can be leftover outside of the parenthesis.
return re.sub("((\(|\[).*(\)|\]))", "", s).strip()
print(remove_unwanted("[some text] abcdef"))
>>> "abcdef"
print(remove_unwanted("(example) somestuff"))
>>> "somestuff"

Checking Palindrome text, with ignored punctuation marks, spaces and case

Homework exercise:
Checking whether a text is a palindrome should also ignore punctuation, spaces and case. For example, "Rise to vote, sir." is also a palindrome but our current program doesn't say it is. Can you improve the above program to recognize this palindrome?
origin code:
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input('Enter text: ')
if (is_palindrome(something)):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
my try:
import re
def reverse(text):
global words
words = text.split()
return words[::-1]
def is_palindrome(text):
return words==reverse(text)
something = input('Enter text: ')
if (is_palindrome(something)):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
Error:
Enter text: jfldj
Traceback (most recent call last):
File "/Users/apple/PycharmProjects/Problem Solving/user_input.py", line 13, in <module>
print("Yes, it is a palindrome")
File "/Users/apple/PycharmProjects/Problem Solving/user_input.py", line 10, in is_palindrome
NameError: name 'words' is not defined
How should I change my code?
Latest code:
import string
def remove_punctuations(word):
return "".join(i.lower() for i in word if i not in string.ascii_letters)
def reverse(text):
return text[::-1]
def is_palindrome(text):
text = remove_punctuations(text)
return text == reverse(text)
something = input('Enter text: ')
if (is_palindrome(something)):
print("Yes, it is a palindrome"
else:
print("No, it is not a palindrome")
No matter what I input, output is Yes.
Enter text: hggjkgkkkk
Yes, it is a palindrome
What's wrong?
To ignore the punctuations, spaces and case of the given text you need to define a function remove_punctuations() which takes a word as parameter and returns a word with all lower case characters, remove punctuation marks and removed spaces.
To remove the unwanted characters we need to iterate over the given text, if the current character falls in strings.ascii_letters , then generate the character converting it to lower caps using str.lower() method. Finally using "".join() method to concatenate the generated str elements.
import string
def remove_punctuations(word):
return "".join(i.lower() for i in word if i in string.ascii_letters)
def reverse(text):
return text[::-1]
def is_palindrome(text):
text = remove_punctuations(text)
return text==reverse(text)
something = "Rise to vote, sir."
if (is_palindrome(something)):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
Since the hint says to use a tuple with forbidden punctuation marks, I created the following variant:
forbidden = (' ', ',', "'", '?', '!', '.', '’')
def reverse(text):
return text[::-1]
def cleaning(text):
clean_text = ''
for item in text:
if item not in forbidden:
clean_text += item
return clean_text
def is_palindrome(text):
lower_text = cleaning(text.lower())
return lower_text == reverse(lower_text)
example = input('Enter something: ')
if is_palindrome(example):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
The cleaning function checks each character for belonging to a tuple of forbidden characters, if not, then concatenates it to the clean_text string
I started studying for python 2 days before so that is what i come up with.
It is not so much advanced but works like a charm. :D
It is pretty straight forward what i do there. I just make a tuple with the "legal" letters (abc=). Then I define a function that 1st change all letters to lower case and then checks every character in the string with the "legal" letters. Then after this "filtering" the rawtext contains only the "legal" ones. Then the 2nd function just reverses the results of the 1st one. Compare and da da..!
# Palindrome recognize
abc='abcdefghijklmnopqrstuvwxyz'
def rawtext(text):
rawtext=''
text=text.lower()
for j in text[::1]:
for i in abc[::1]:
if j==i:
rawtext=rawtext+j
return rawtext
def reverse(text):
rev= rawtext(text)[::-1]
return rev
text=str(input('Write text:'))
if reverse(text)==rawtext:
print('The text is palindrome')
else:
print('The text is not a palindrome')
from itertools import izip_longest
def is_palindrome(s):
l = len(s)
fi = (i for i in xrange(l) if s[i].isalpha())
bi = (i for i in xrange(l-1, -1, -1) if s[i].isalpha())
for f, b in izip_longest(fi, bi):
if f >= b: return True
if s[f].lower() != s[b].lower(): return False
return True
Hope that helps

Python3 using re.match to check if password hold certain characters

I am trying to return the password entered by a user if it matches a-z,A-Z,0-9,_,- otherwise a ValueError will be executed within a try clause. Here is my line of code that doesn't seem to be working as it allows just about anything like (?.,##$%^*)
return re.match('^[A-Za-z0-9_-]*$',password)
With the Kleene closure, you allow an empty string as a correct password. You can use the + special character to match one repetitions of the valid characters:
def validate(password):
match = re.match('^[a-z0-9_-]+$', password, re.I)
if match is not None:
return password
else:
raise ValueError
Outline
Using sets and set-subtraction is likely a simpler solution.
Code
from string import ascii_letters, digits
PASSWORD_SET = set(ascii_letters + digits + "_-")
def has_only_password_letters(candidate):
return not(set(candidate) - PASSWORD_SET)
or:
def has_only_password_letters(candidate):
return all(c in PASSWORD_SET for c in candidate)
Tests
>>> def test_password(password):
... if has_only_password_letters(password):
... print "Okay: ", password
... else:
... print "Nuh-uh: ", password
...
>>> test_password("asdasd123123")
Okay: asdasd123123
>>> test_password("asdasd123123!!!")
Nuh-uh: asdasd123123!!!
Here is a non-regex solution using isalnum:
for c in password:
if not (c.isalnum() or c in ['_', '-']):
raise ValueError('Invalid character in password')

Categories