How to check if last character is integer in raw_input - python

basically i want the script to check the last digit of the raw_input to see if it's integer or not. if integer print true, else print false
here is the code:
word = raw_input("input your alphanumeric word:")
end = re.search(r'\d+$', word)
if end is not None:
print "numeric digit should be last"
else
print "true"

Regex is an overkill for problems as simple as this. Simply index the last element word[-1] and check if its a digit via the builtin String method str.isdigit
word[-1].isdigit()
Note, you may have to consider the fact that the word may be an empty string and have to handle it appropriately.
bool(word) and word[-1].isdigit()
or as suggested by #iCodez use slicing instead of indexing, as slicing would not throw index error for empty string
word[-1:].isdigit()
Example
>>> word = raw_input("input your alphanumeric word:")
input your alphanumeric word:asdf
>>> bool(word) and word[-1].isdigit()
False
>>> word = raw_input("input your alphanumeric word:")
input your alphanumeric word:asd1
>>> bool(word) and word[-1].isdigit()
True
>>> word = raw_input("input your alphanumeric word:")
input your alphanumeric word:
>>> bool(word) and word[-1].isdigit()
False

You can look at the last character of the string using slicing [-1], and use the string method isdigit to see if it is a number.
s1 = 'hello world'
s2 = 'hello again3'
>>> s1[-1].isdigit()
False
>>> s2[-1].isdigit()
True

print 'true' if re.search(r'\d$', word) else 'false'
You could also use:
print 'true' if word[-1].isdigit() else 'false'
...but this will throw an IndexError if the word is zero-length.

Related

How to find if the given strings can be found inside the second strings [duplicate]

This question already has answers here:
Does Python have a string 'contains' substring method?
(10 answers)
How do I do a case-insensitive string comparison?
(15 answers)
Closed last month.
I would like to know how to write a function that returns True if the first string, regardless of position, can be found within the second string by using two strings taken from user input. Also by writing the code, it should not be case sensitive; by using islower() or isupper().
Example Outputs:
1st String: lol
2nd String: Hilol
True
1st String: IDK
2nd String: whatidk
True
My code:
a1 = str(input("first string: "))
a2 = str(input("second string: "))
if a2 in a1:
print(True)
else:
print(False)
It outputs:
1st String: lol
2nd String: lol
True
1st String: lol
2nd String: HIlol
False #This should be true, IDK why it is false.
I only came this far with my code. Hoping someone could teach me what to do.
Is this what you're looking for?
string_1 = input("first string: ")
string_2 = input("second string: ")
if string_1.lower() in string_2.lower():
print(True)
else:
print(False)
A "function" would be:
def check_occuring(substring, string):
if substring.lower() in string.lower():
return True
else:
return False
string_1 = input("first string: ")
string_2 = input("second string: ")
print(check_occuring(string_1, string_2))
Please note that you can also just print or return substring.lower() in string.lower()
If you want the Program to be case sensitive, just make everything lowercase
substring = input("substring: ").lower()
text = input("text: ").lower()
To check if a substring can be found in another string can be done by using the keyword in
>>> "lol" in "HIlol"
True
maybe check your inputs here. The whole program would be
substring = input("substring: ").lower()
text = input("text: ").lower()
print(substring in text)
note: <str> in <str> gives you a boolean so you can use it in if conditions. In this case you can just print the boolean directly.

How to check if individual character in a string exists in another string for python

Is there any library that allows me to check If all the individual characters in one string exists in another string. When i try to use in what happens is the character has to be a substring. It only works for 1234 and 123. However i want something that checks individual characters. I want a library that gives me the output: string 2 is in string 1 for the following code.
string1 = '1234'
string2 = '24'
if string2 in string1:
print('string2 is in string1')
else:
print('string2 is not in string1')
You can use all() with a generator. This returns a true only if all conditions are a true else false:
string1 = '1234'
string2 = '24'
if all(x in string1 for x in string2):
print('string2 is in string1')
else:
print('string2 is not in string1')
Or, you can use set's issubset:
set(string2).issubset(string1)

How to check that a string contains only “a-z”, “A-Z” and “0-9” characters [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 3 years ago.
I am importing string and trying to check if text contains only "a-z", "A-Z", and "0-9".
But I get only input and it doesn't print success when I enter letters and digits
import string
text=input("Enter: ")
correct = string.ascii_letters + string.digits
if text in correct:
print("Success")
You could use regex for this, e.g. check string against following pattern:
import re
pattern = re.compile("[A-Za-z0-9]+")
pattern.fullmatch(string)
Explanation:
[A-Za-z0-9] matches a character in the range of A-Z, a-z and 0-9, so letters and numbers.
+ means to match 1 or more of the preceeding token.
The re.fullmatch() method allows to check if the whole string matches the regular expression pattern. Returns a corresponding match object if match found, else returns None if the string does not match the pattern.
All together:
import re
if __name__ == '__main__':
string = "YourString123"
pattern = re.compile("[A-Za-z0-9]+")
# if found match (entire string matches pattern)
if pattern.fullmatch(string) is not None:
print("Found match: " + string)
else:
# if not found match
print("No match")
Just use str.isalnum()
>>> '123AbC'.isalnum()
True
>>> '1&A'.isalnum()
False
Referencing the docs:
Return true if all characters in the string are alphanumeric and there
is at least one character, false otherwise. A character c is alphanumeric
if one of the following returns True: c.isalpha(), c.isdecimal(),
c.isdigit(), or c.isnumeric().
If you don't want str.isdigit() or str.isnumeric() to be checked which may allow for decimal points in digits just use str.isnumeric() and str.isalpha():
>>> all(c.isnumeric() or c.isalpha() for c in '123AbC')
True
>>> all(c.isnumeric() or c.isalpha() for c in '1&A')
False
You must compare each letter of the incoming text separately.
import string
text = input("Enter: ")
correct = string.ascii_letters + string.digits
status = True
for char in text:
if char not in correct:
status = False
if status:
print('Correct')
else:
print('InCorrect')
You are testing if the entire string is in the string 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
So say the input is 'testInput'
You are checking if 'testInput' is in the string 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' which it is not.
You need to check each character individually
You can do this with a function for ease of use
import string
def validCharacters(text):
correct = string.ascii_letters + string.digits
for character in text:
if character not in correct:
return False
return True
text = input("Enter: ")
if validCharacters(text):
print("Correct")
else:
print("Incorrect")
We can remove all characters that aren't A-Z, a-z, or 0-9 then check the length of the remaining string. If it's greater than 0, there are characters that aren't the ones above:
import re
text = input("Enter: ")
result = re.sub("[A-Za-z0-9]", '', text)
if len(result) == 0:
print("Success")
else:
print("Failure")
Result:
abcDEF123 -> Success
hello! -> Failure
You can do it in many various ways, I would harness sets for that following way:
import string
correct = {char for char in string.ascii_letters + string.digits}
def is_correct(text):
return {char for char in text}.issubset(correct)
print(is_correct('letters123')) # True
print(is_correct('???')) # False
print(is_correct('\n')) # False
I simply check if set consisting of characters of given text is subset of set of all legal characters. Keep in mind that this always process whole text, which is not best from performance point of view (as you might end check after you find first illegal character), but it should not be problem unless you need to deal with very long texts or in very small amount of time.
You can use regex match for checking if the string contains only alpha and letters
import re
text = input("enter:")
regex = r"([0-9a-zA-Z]+)"
match = re.match(regex, string)
if match != None:
print("success")

python regex matching "ab" or "ba" words

I tried matching words including the letter "ab" or "ba" e.g. "ab"olition, f"ab"rics, pro"ba"ble. I came up with the following regular expression:
r"[Aa](?=[Bb])[Bb]|[Bb](?=[Aa])[Aa]"
But it includes words that start or end with ", (, ), / ....non-alphanumeric characters. How can I erase it? I just want to match words list.
import sys
import re
word=[]
dict={}
f = open('C:/Python27/brown_half.txt', 'rU')
w = open('C:/Python27/brown_halfout.txt', 'w')
data = f.read()
word = data.split() # word is list
f.close()
for num2 in word:
match2 = re.findall("\w*(ab|ba)\w*", num2)
if match2:
dict[num2] = (dict[num2] + 1) if num2 in dict.keys() else 1
for key2 in sorted(dict.iterkeys()):print "%s: %s" % (key2, dict[key2])
print len(dict.keys())
Here, I don't know how to mix it up with "re.compile~~" method that 1st comment said...
To match all the words with ab or ba (case insensitive):
import re
text = 'fabh, obar! (Abtt) yybA, kk'
pattern = re.compile(r"(\w*(ab|ba)\w*)", re.IGNORECASE)
# to print all the matches
for match in pattern.finditer(text):
print match.group(0)
# to print the first match
print pattern.search(text).group(0)
https://regex101.com/r/uH3xM9/1
Regular expressions are not the best tool for the job in this case. They'll complicate stuff way too much for such simple circumstances. You can instead use Python's builtin in operator (works for both Python 2 and 3)...
sentence = "There are no probable situations whereby that may happen, or so it seems since the Abolition."
words = [''.join(filter(lambda x: x.isalpha(), token)) for token in sentence.split()]
for word in words:
word = word.lower()
if 'ab' in word or 'ba' in word:
print('Word "{}" matches pattern!'.format(word))
As you can see, 'ab' in word evaluates to True if the string 'ab' is found as-is (that is, exactly) in word, or False otherwise. For example 'ba' in 'probable' == True and 'ab' in 'Abolition' == False. The second line takes take of dividing the sentence in words and taking out any punctuation character. word = word.lower() makes word lowercase before the comparisons, so that for word = 'Abolition', 'ab' in word == True.
I would do it this way:
Strip your string from unwanted chars using the below two
techniques, your choice:
a - By building a translation dictionary and using translate method:
>>> import string
>>> del_punc = dict.fromkeys(ord(c) for c in string.punctuation)
s = 'abolition, fabrics, probable, test, case, bank;, halfback 1(ablution).'
>>> s = s.translate(del_punc)
>>> print(s)
'abolition fabrics probable test case bank halfback 1ablution'
b - using re.sub method:
>>> import string
>>> import re
>>> s = 'abolition, fabrics, probable, test, case, bank;, halfback 1(ablution).'
>>> s = re.sub(r'[%s]'%string.punctuation, '', s)
>>> print(s)
'abolition fabrics probable test case bank halfback 1ablution'
Next will be finding your words containing 'ab' or 'ba':
a - Splitting over whitespaces and finding occurrences of your desired strings, which is the one I recommend to you:
>>> [x for x in s.split() if 'ab' in x.lower() or 'ba' in x.lower()]
['abolition', 'fabrics', 'probable', 'bank', 'halfback', '1ablution']
b -Using re.finditer method:
>>> pat
re.compile('\\b.*?(ab|ba).*?\\b', re.IGNORECASE)
>>> for m in pat.finditer(s):
print(m.group())
abolition
fabrics
probable
test case bank
halfback
1ablution
string = "your string here"
lowercase = string.lower()
if 'ab' in lowercase or 'ba' in lowercase:
print(true)
else:
print(false)
Try this one
[(),/]*([a-z]|(ba|ab))+[(),/]*

How can I tell if a string only contains letter AND spaces

I'm having trouble figuring out the above question and have a felling I should be testing every character with "for character in string" however I cant really figure out how that would work
This is what I have now but I know it doesnt work as intended because it only allows me to test letters but I also need to know spaces so for example " MY dear aunt sally" should say yes contains only letters and spaces
#Find if string only contains letters and spaces
if string.isalpha():
print("Only alphabetic letters and spaces: yes")
else:
print("Only alphabetic letters and spaces: no")
You can use a generator expression within all built-in function :
if all(i.isalpha() or i.isspace() for i in my_string)
But note that i.isspace() will check if the character is a whitespace if you just want space you can directly compare with space :
if all(i.isalpha() or i==' ' for i in my_string)
Demo:
>>> all(i.isalpha() or i==' ' for i in 'test string')
True
>>> all(i.isalpha() or i==' ' for i in 'test string') #delimiter is tab
False
>>> all(i.isalpha() or i==' ' for i in 'test#string')
False
>>> all(i.isalpha() or i.isspace() for i in 'test string')
True
>>> all(i.isalpha() or i.isspace() for i in 'test string')
True
>>> all(i.isalpha() or i.isspace() for i in 'test#string')
False
just another way for Fun, I know its not that good:
>>> a
'hello baby'
>>> b
'hello1 baby'
>>> re.findall("[a-zA-Z ]",a)==list(a) # return True if string is only alpha and space
True
>>> re.findall("[a-zA-Z ]",b)==list(b) # returns False
False
Cascade replace with isalpha:
'a b'.replace(' ', '').isalpha() # True
replace returns a copy of the original string with everything but the spaces. Then you can use isalpha on that return value (since the return value is a string itself) to test if it only contains alphabet characters.
To match all whitespace, you're probably going to want to use Kasra's answer, but just for completeness, I'll demonstrate using re.sub with a whitespace character class:
import re
re.sub(r'\s', '', 'a b').isalpha()
The below re.match fucntion would return a match object only if the input contain alphabets or spaces.
>>> re.match(r'[A-Za-z ]+$', 'test string')
<_sre.SRE_Match object; span=(0, 11), match='test string'>
>>> re.match(r'(?=.*? )[A-Za-z ]+$', 'test#bar')
>>>

Categories

Resources