python make sure that word is capitalized - python

I'm trying to make sure that every word that is typed is uppercased as in ABC. The code I'm working with is this
abbreviate=input("Abbreviation: ")
words=abbreviate[0:6]
numbers = abbreviate[6:8]
if len(abbreviate)==9:
if words.isalpha: #I think it's also possible to use.if str(words)?
if words.isupper: #(i did upper first, what is the difference?)
if int(numbers):
print("correct")
else:
print("wrong, you need numbers")
else:
print("wrong, all words are supposed to be uppercase")
else:
print("wrong, it needs to be words(alphabet)")
else:
print("wrong, the length needs to be 8")
QWERTY567 should be correct.
qwerty567 should be incorrect.
How do I go on doing this?
qwerty333
012345678

IIUC In order to just verify, whether first 5 characters are uppercase letters, and next 4 are digits, you can do:
import re
abbreviate=input("Abbreviation: ")
if(re.match(r"^[A-Z]{5}\d{4}", abbreviate)):
print("correct!")
else:
print("wrong!")
If moreover you want to ensure it's only 9 characters in total (i.e. input consists of exactly 5 uppercase letters first, then 4 digits) you can do:
import re
abbreviate=input("Abbreviation: ")
if(re.match(r"^[A-Z]{5}\d{4}$", abbreviate)):
print("correct!")
else:
print("wrong!")

str.isalpha and str.isupper are methods. You need to call them to get a result:
if words.isalpha():
if words.isupper():
About your comments
I think it's also possible to use if str(words)?
No, str(words) would do nothing. input() returns a string, so words is already a string.
I did upper first, what is the difference?
str.upper converts a string to uppercase, e.g. 'a'.upper() == 'A'
By the way
int() doesn't return a Boolean. It might be better to use str.isnumeric to check if numbers is numeric instead.
It's simpler to use guard clauses than nested conditionals:
if len(abbreviate) != 9:
print("wrong, the length needs to be 9")
elif not words.isalpha():
print("wrong, the abbreviation must be alphabetic")
...
else:
print("correct")

Use a regular expression:
^[A-Z0-9]+$
See a demo on regex101.com.

If you have all letters and then at a certain index, you have all numbers, I would suggest:
abbreviation=input("Abbreviation: ")
i = len(abbreviation)
for n, char in enumerate(abbreviation):
if char.isalpha() and char.isupper():
pass
else:
i = n
break
for char in abbreviation[i:]:
if char.isnumeric():
pass
else:
print('Wrong')
https://www.geeksforgeeks.org/python-string-isnumeric-application/
https://www.geeksforgeeks.org/isupper-islower-lower-upper-python-applications/
You find the first non-lowercase letter, and then everything after it should be all numeric. If you need at least 1 uppercase letter, you can also modify that. Please tell me if you have questions!

If the value of abbreviate is 'QWERTY567', then you should edit your code with words = abbreviate[0:6] , numbers = abbreviate[6:8] , isalpha() and isupper() for it to work.

Related

Why doesn't if any(var0) == any(var1) work?

I'm very new to programming, and more new to Python, and I'm having a hard time figuring this out. I'm trying to make a simple text hangman game, and I'm trying to validate player1's input. Here's what I have so far.
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
d = list(d)
print(d)
if any(int) == any(d):
print("Invalid input. Please choose a non-number with no spaces or special characters.")
I can't figure why, whether I include a number in my response or not, it always meets my any(int) == any(d) condition. I know I must just be misunderstanding how any() works.
You are right: the issue is with how you use the any() function. any() returns either True or False depending on whether or not any of the elements in its iterable argument are True, in other words if they exist and are not False or an empty list or empty string or 0. This will always evaluate as True for int because int does contain an element that is True and the same will happen for d unless you do not give any input when the input() function prompts you (you hit return without typing anything). What your conditional is basically asking is the following:
if True==True
To fix this, just change your code to the following:
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
print(d)
for letter in d:
if letter in int:
print("Invalid input. Please choose a non-number with no spaces or special characters.")
break
The easiest solution, however, does not involve the int list at all. There is actually a special method in python that can gauge whether or not a string has a number (or special character) in it, and this method, .isalpha() can be used to streamline this process even further. Here's how to implement this solution:
while True:
d = input("Please choose any word by typing it here: \n")
print(d)
if not d.isalpha():
print("Invalid input. Please choose a non-number with no spaces or special characters.")
Try this:
a = 0
ints = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
word = input()
word_list = list(word)
if any(letter in ints for letter in word_list):
print("Invalid input. Please choose a non-number with no spaces or special characters.")

Python - Regex - True Or False

So what i want is for my code to understand if my input has a number in it or not, if it does it is meant to output "Correct" but if it doesn't then it would output "Incorrect" how can i actually make this work. So it knows if there is an integer in the input or not. Any help is appreciated
import re
yourString=input()
number = re.search(r'\d+', yourString).group()
if number == True:
print("Correct")
else:
print("Incorrect")
According to https://docs.python.org/3/library/re.html#match-objects you have a bit of a subtle error.
The statement should not be if number == True: it should be if number:, the reason being the value number is tests as True if anything is matched, and is None if there are no matches.
i.e.
import re
yourString=input()
number = re.search(r'\d+', yourString)
if number:
print("Correct")
group = number.group()
else:
print("Incorrect")
Note, somewhat bizarrely
import re
yourString=input()
number = re.search(r'\d+', yourString)
if number:
print(number == True)
group = number.group()
else:
print("Incorrect")
Prints false, so number is not the value true, it overrides __bool__. See https://docs.python.org/3/reference/datamodel.html#object.bool for more information
You can use str.isdigit, re.search, or the built-in string to number conversions such as float and int:
def extractNumber(string):
for word in string.split():
try:
# The float() function accepts a decimal string.
# The int() function accepts an integer string.
return float(word)
except ValueError:
pass
number = extractNumber(input())
if number is not None:
print('Your number is: {}'.format(number))
else:
print('No number found')
the regex you're looking for is: \w*[0-9]+\w*. It accepts anything that contains at least one digit.
\w* is the same as [a-zA-Z0-9_]* meaning it will match any lower/upper -case letter, digit or _ literally. It can occur 0 to many times in the string
[0-9]+ matches one to many digits from 0 to 9.
Actually, if your intention is just to check whether the string has digits you are good to go just with [0-9]+ that's the same of what you posted originally.
You can try and create regexes using this site regex101.com

How to check if a word is a palindrome (Python)

Please help...
So the instruction says to program the computer to check whether a word is a palindrome or not. I inputted this code:
def is_palindrome(word):
counter_from_first_letter=0
counter_from_last_letter=-1
from_first_letter = word[counter_from_first_letter]
from_last_letter = word[counter_from_last_letter]
max_index_from_first= len(word)
max_index_from_last= (len(word))*-1
while from_first_letter == from_last_letter:
from_first_letter = word[counter_from_first_letter]
from_last_letter = word[counter_from_last_letter]
counter_from_first_letter += 1
counter_from_last_letter -= 1
return True
The problem is the computer only checks whether the first and last letters are the same, and if they are, it just returns true. How do I make sure the computer checks every single letter? Thanks
Maybe something like this:
def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False
in python-3
name = 'madam'
print(name.find(name[::-1]) == 0)
Maybe you can try this: first convert your string into a list, then reverse the list and convert it back into a string. compare both the strings and if they match? they are palindromes, if not, they aren't.
'''checking whether a word is a palindrome
we first convert the word into a list then join it;
use an if statement to compare the two strings'''
def palindrome(string):#you need the input(string)
palindrome_check=[]#create an empty list
for character in string [::-1]:#create a list from the input
#(use a for loop because you now know the range)
#the [::-1] analyzes the characters in reverse
palindrome_check.append(character)#add each character to the new empty list
#print(palindrome_check)
rev_string= ''.join(palindrome_check)#.join -creates a string from the created list
print(rev_string)
#REMOVE SPECIAL CHARACTERS- IM THINKING OF A LOOPING THROUGH, BUT NOT SURE HOW TO IMPLEMENT IT
string=string.replace(' ', '')
rev_string=rev_string.replace(' ', '')
string=string.replace(',', '')
rev_string=rev_string.replace(',', '')
string=string.replace('.', '')
rev_string=rev_string.replace('.', '')
#THIS IS THE LOGIC: IT CHECKS BOTH STRINGS, if they are equal, it is a palindrome;
if string.lower()==rev_string.lower():
return True, print('It is a Palindrome')
else:
return False, print('It isnt a palindrome')
#call the function; key in the parameters-
palindrome= palindrome("No, Mel Gibson Is A Casinos Big Lemon")
#maybe we can try having a user key in the parameter? lets try
#palindrome=palindrome(input('kindly enter your word/phrase '))-wrong
#print('Kindly enter your word or phrase')
#user_palindrome=input('')
#palindrome=palindrome(user_palindrome)
#it wont work this way either
If you can have the user define the parameter(string), the better, if you know how to do this, kindly share.
To check whether a word or phrase is a palindrome, it be necessary to check if the original sentence is equal to the original sentence reversed.
word = "Eva can I see bees in a cave"
word_lower = word.lower().replace(" ", "")
if word_lower == word_lower[::-1]:
print("It's a palindrome")
else:
print("This is not a palindrome")

Notify user when they got a letter correct in a char list Python

How would I go about telling the user when they've got the correct letter in a list? Only way I know of is to insert the index, but that doesn't feel very flexible, especially when the words vary in length.
import random
possibleWords = [["apple"], ["grapefruit"], ["pear"]]
randomWord = random.choice(possibleWords)
anotherWord = ''.join(randomWord)
finalWord = list(anotherWord)
maxTries = list(range(0, 11))
attemptsMade = 0
triesLeft = 10
print("Hangman!")
print("\nYou got {} tries before he dies!".format(maxTries[10]))
print("There's {} possible letters.".format(len(finalWord)))
for tries in maxTries:
userChoice = input("> ")
if userChoice == finalWord[0]:
print("You got the first letter correct! It is {}.".format(finalWord[0]))
else:
print("Ouch! Wrong letter! {} tries remaining.".format(triesLeft))
attemptsMade += 1
triesLeft -= 1
Talking about characters in lists, or - what i think is more likely in your case - chars in words you can just check for
if userChoice in finalWord:
# [...] do stuff here
and further on use the index function to determine the position (or positions if multiple occurence).
finalWord.index(userChoice)
You could sure also go the way using index() function directly and work your way using the return values.
Use Python's "in" keyword to check if something is within a list/iterable.
if userChoice in finalWord:
Though for this, I'd just use regex or list comprehension to get the indexes while you are at it, since you might want them for the game.
char_indexes = [i for (i, l) in enumerate(finalWord) if l == userChoice]
if len(char_indexes):
Use a set for the letters that are in the word, and whenever the player guesses a letter, check if the letter is still in the set. If it’s not, it was a wrong letter; if it is, then remove that letter and just continue. If the set is empty at some point, then the player guessed all letters of the word.
Something to get you started:
def hangman (word):
letters = set(word.lower())
attempts = 5
while attempts > 0:
guess = input('Guess a character ')
if guess[0].lower() in letters:
print('That was correct!')
letters.remove(guess[0])
else:
print('That was not correct!')
attempts -= 1
if not letters:
print('You solved the word:', word)
return
hangman('grapefruit')

Having trouble learning how to look at individual characters in a string checking for case or digit

I am trying to write a simple password checker for homework assignment, looking for at least one capital, one lower case, one digit, and it needs to be 6 or more chars.
I have searched and searched on here and elsewhere, but either what I read doesn't match our instruction, or the replies are more advanced than myself. Any help I get will be cited as a comment in my assignment.
This is just the part of my code which checks for caps, it only looks at the whole string, not the individual characters and I can't seem to find the solution.
passwd = input('enter password: ') ## we are actually using (sys.agrv)
## but I am using this for testing
character = passwd[0:]
lcase_bad = False
for character in passwd:
if not character.islower() > 1:
lcase_bad = True
if lcase_bad:
print('Password must include lowercase letters ')
else:
print('password accepted')
for character in passwd:
Here you're iterating through each letter of the input.
When you do if not character.islower() > 1:, it will always be True. .islower() returns either True or False, depending on if the string is a capital letter or not. not False == 1, because boolean is a subclass of int. not True == 0. Both are not greater than one.
You can just do something like:
capital = False
lowercase = False
number = False
if len(passwd) < 6:
print 'That was not more than 6 characters'
else:
for character in passwd:
if character.islower():
lowercase = True
elif character.isupper():
capital = True
elif character.isdigit():
number = True
if capital and lowercase and number:
break
else:
print 'That did not have a capital letter, lowercase letter, and a digit'
Of course this is useful if you want to tell the person what the password didn't have. However, you can also just do one test instead.
Just check for all those conditions one after another:
mystring = input("enter password: ")
if any(c.isupper() for c in mystring) \ # There is an uppercase letter
and any(c.islower() for c in mystring) \ # There is a lowercase letter
and any(c.isdigit() for c in mystring) \ # There is a number
and len(mystring) > 5: # The length is 6 or greater
# string passed all tests
else:
# One or more tests failed--input is bad.
You've almost got it! If you remove the > 1 from your code (which won't really do anything useful), you get this:
lcase_bad = False
for character in passwd:
if not character.islower():
lcase_bad = True
It just happens that this will test to see if the entire string is made of lowercase letters. If it is, lcase_bad will remain False; otherwise, it will become True. It should not be an extreme leap of faith to see that if you flip the False and True around and call it lcase_good, you can see whether at least one character is lowercase.
As iCodez notes, you can also rewrite it using any with a generator comprehension. It reads fairly easily:
if any(character.islower() for character in passwd):
However, you probably haven't gotten to generator comprehensions, so it might be best to stay with a for loop for clarity's sake.

Categories