String must contain multiple words - python

I'm new to Python and I have a question.
I am making a simple chatbot and I want it to give answers to questions and things like that.
Here is an example:
def ChatMode():
ChatCommand = raw_input ("- user: ")
if "quit" in ChatCommand :
print "Lucy: See you later."
print ""
UserCommand()
else :
print "Lucy: sorry i don\'t know what you mean."
ChatMode()
For something more advanced I need it to check for 2 strings.
I tried some things like:
def ChatMode() :
ChatCommand = raw_input ("- user: ")
if "quit" + "now" in ChatCommand :
print "Lucy: See you later."
print ""
UserCommand()
else :
print "Lucy: sorry i don\'t know what you mean."
ChatMode()
But that made "quitnow".
I also tried to replace the + with an & but that gave me an error:
TypeError: unsupported operand type(s) for &: 'str' and 'str'
Does anyone have a short code to do this? I don't want 5+ sentences, I want to keep it as short as possible.

Use separate clauses to check if both "quit" and "now" are in the ChatCommand e.g.
if "quit" in ChatCommand and "now" in ChatCommand:
Note that in Python, the logical and operator && is and, and & is the bitwise and.

if "quit" in ChatCommand and "now" in ChatCommand:
Also, as a bit of style, in Python CamelCase is usually reserved for Classes.

Use all():
if all(word in ChatCommand for word in ("quit", "now")):
If you want to avoid matching quit within quite, you can use a regex:
import re
if all(re.search(regex, ChatCommand) for regex in (r"\bquit\b", r"\bnow\b")):
because the \b word boundary anchors only match at the start and end of a word.

Related

How to accept user input and run an 'if statement' on one line of code

I want to create a more pythonic code line to take a string input from a user and then check to see if the string is a palinadrome (i.e. a reversable word like "racecar").
I have tried this code below and functionally it works ok, but I want to improve it:
word = "Racecar".lower()
print("Palindrome" if word == word[::-1] else "Not Palindrome")
But ideally what I want is to be able to produce a code line something like this:
word = input() if word == word[::-1],print("Palindrome" else "Not Palindrome")
I can't get the code to work and need some advise on how to structure the code accept an input and then perform an IF function work with a result being printed out.
Thanks for any help.
Python 3.8 has the walrus operator (Assignment expressions),
print("Palindrome" if (c := input().lower()) == c[::-1] else "Not palindrome")

How can I test if a variable equals any of several options?

I am helping a friend with some code for a school helping bot, but I've run into a problem. On the last line, where it says: if helpselect == ('*****'): , I am trying to add multiple conditions in one line of code so that the specific line of code activates when they type math or math. HELP
import time
print('Hello, my name is CareBot and I am here to help!')
time.sleep(3)
name = input('Please input your name: ')
print('Nice to meet you, %s. I am a bot that can lead you to resources to help out with school subjects!' % name)
time.sleep(2)
print('Now, what subject can I help you with?')
helpselect = input('Please input a subject: ')
if helpselect == ('*****'):
if helpselect in {"math", "english"}:
print("You selected math or english")
Something like that? (You said "when they type math or math", which is redundant.)
If you're just trying to check if the person typed a certain subject then I might create a set of strings. When you check if something is in a set of strings you are checking whether or not the word you typed is one of the words in the set of strings.
setofstrings = ["math", "english", "science"]
if helpselect in setofstrings:
or perhaps you want to do this.
if helpselect == "math" or helpselect == "english":
If you're trying to check if there are any math symbols in a line of code.
What I would do is create a string called mathsymbols.
mathsymbols = "+-*/"
Then check and see if the input contains any math symbols by doing this line of code. This checks if what you typed any individual character in the string mathsymbols.
if helpselect in mathsymbols:
I would want learn sets, strings, the "in" operator, "and", "or", etc.

Input a message inside a box

I need to create a box with parameters that prints any input the user puts in. I figured that the box should be the length of the string, but I'm stuck with empty code, because I don't know where to start.
It should look like this:
I agree with Daniel Goldfarb comments. Don't look for help without trying.
If you still couldn't get how to do that, then only read my remaining comment.
Just print :
str = string entered
len(str) = string length
+-(len(str) * '-')-+
| str |
+-(len(str) * '-')-+
So hopefully you can learn, don't want to just write the code for you. Basically break it into steps. First you need to accept user input. If you don't know how to do that, try googling, "python accept user input from stdin" or here is one of the results from that search: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Then, as you mentioned, you need the length of the string that was input. You can get that with the len function. Then do the math: It looks like you want "|" and two spaces on each side of the string, giving the length plus 6 ("| " on either side). This new length is what you should make the "+---+" strings. Use the print() function to print out each line. I really don't want to say much more than that because you should exercise your brain to figure it out. If you have a question on how to generate "+---+" of the appropriate length (appropriate number of "-" characters) you can use string concatenation and a loop, or just use the python string constructor (hint: google "construct python string of len repeat characters"). HTH.
One more thing, after looking at your code, in addition to my comment about printing the string itself within the box, I see some minor logic errors in your code (for example, why are you subtracting 2 from the width). THE POINT i want to me here is, if you ware going to break this into multiple small functions (a bit overkill here, but definitely a good idea if you are just learning as it teaches you an important skill) then YOU SHOULD TEST EACH FUNCTION individually to make sure it does what you think and expect it to do. I think you will see your logic errors that way.
Here is the solution, but I recommend to try it out by yourself, breakdown the problem into smaller pieces and start from there.
def format(word):
#It declares all the necessary variables
borders =[]
result = []
# First part of the result--> it gives the two spaces and the "wall"
result.append("| ")
# Second part of the result (the word)
for letter in word:
result.append(letter)
# Third part of the result--> Ends the format
result.append(" |")
#Transforms the list to a string
result = "".join(result)
borders.append("+")
borders.append("--"+"-"*len(word)+"--")
borders.append("+")
borders="".join(borders)
print(borders)
print(result)
print(borders)
sentence = input("Enter a word: ")
format(sentence)
I'm new to Python, and I've found this solution. Maybe is not the best solution, but it works!
test = input()
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
print("| " + test + " |")
print("+-", end='')
for i in test:
print("-", end='')
print("-+")

How can I check if a string contains a special letter? [duplicate]

This question already has answers here:
How to check a string for specific characters?
(8 answers)
How to check a string for a special character?
(5 answers)
Closed 5 years ago.
I am building a program that gets a password as a string and checks its strength by a couple of factors. I want to check if the entered string contains a special character (like %,$,# etc.) but so far I couldn't able to figure it out. What is the best way to do so?
Edit: I am not searching for a specific character. I need to search the string to find if it has some kind of a non-letter, non-digit character.
Edit 2 : I want to do it without a loop.
You can possibly use regex!
>>> import re
>>> s='Hello123#'
>>> re.findall('[^A-Za-z0-9]',s)
['#']
>>> if re.findall('[^A-Za-z0-9]',s):print True
...
True
Happy Coding!
Hope it helps!
As you stated you don't want to use a loop, and probably never worked with regexes, how about a list comprehension?
import string
all_normal_characters = string.ascii_letters + string.digits
def is_special(character):
return character not in all_normal_characters
special_characters = [character for character in password if is_special(character)]
Let me know if this works, or if you need more help!
You will have to put his into a for loop to check for special character and I think you need to make a list with them all in and then test it like that but this is the basic code you need! Replace the print bit with whatever else you need to do!
password = "VerySecurePassw0rd"
if "%" in password:
print( "Your Password has a special character in it!")
if "%" not in password:
print ("Your Password does not have a special character in it!")
EDIT:
Or you could use "else" above
Without using a loop I'm not sure however you could use "elif" but it's not very efficient
password = "VerySecurePassw0rd"
if "%" in password:
print ("Your Password has a special character in it!")
elif "$" in password:
print( "Your Password has a special character in it!")
elif "#" in password:
print ("Your Password has a special character in it!")
You could also try this:
if "%" and "$" in password:
print("Your Password has a 2 special characters in it!")
I think that should work

How to verify numbers in input with python?

I'm trying to learn how to program and I'm running into a problem....
I'm trying to figure out how to make sure someone inputs a number instead of a string. Some related answers I found were confusing and some of the code didn't work for me. I think someone posted the try: function, but it didn't work, so maybe I need to import a library?
Here's what I'm trying right now:
Code:
print "Hi there! Please enter a number :)"
numb = raw_input("> ")
if numb != str()
not_a_string = int(next)
else:
print "i said a number, not a string!!!"
if not_a_string > 1000:
print "You typed in a large number!"
else:
print "You typed in a smaller number!"
Also I have another question while I'm asking. How can I make it so it will accept both uppercase and lower case spellings? In my code below, if I were to type in "Go to the mall" but with a lowercase G it would not run the if statement because it only accepts the capital G.
print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep"
answer = raw_input("> ")
if answer == "Go to the mall":
print "Awesome! Let's go!"
elif answer == "Get lunch":
print "Great, let's eat!"
elif answer == "Go to sleep":
print "Time to nap!"
else:
print "Not what I had in mind...."
Thanks. ^^
Edit: I'm also using python 2.7 not 3.0
You can do something like this:
while True: #infinite loop
ipt = raw_input(' Enter a number: ')
try:
ipt = int(ipt)
break #got an integer -- break from this infinite loop.
except ValueError: #uh-oh, didn't get an integer, better try again.
print ("integers are numbers ... didn't you know? Try again ...")
To answer your second question, use the .lower() string method:
if answer.lower() == "this is a lower case string":
#do something
You can make your string comparisons really robust if you want to:
if answer.lower().split() == "this is a lower case string".split():
In this case, you'll even match strings like "ThIs IS A lower Case\tString". To get even more liberal in what you accept, you'd need to use a regular expression.
(and all this code will work just fine on python2.x or 3.x -- I usually enclose my print statements in parenthesis to make it work for either version).
EDIT
This code won't quite work on python3.x -- in python3, you need to change raw_input into input to make it work. (Sorry, forgot about that one).
First,you should ask only one question per post.
Q1: use built-in .isdigit()
if(numb.isdigit()):
#do the digit staff
Q2:you can use string.lower(s) to solve the capital issue.
you may try
numb = numb.strip()
if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit():
# process numb

Categories