Getting python to seaarch for specific words in an input - python-3.x

I have been trying to create a basic program (to later incorporate into a bigger one) that searches for specific words within a user input, here is what I originally did:
command=input(">")
for "hi" in command():
print("Hello there.")
I thought this would search for "hi" in the user input and if it found the word, it would say hi back, this did not work so I tried using variables instead:
command=input(">")
string = "hi"
for string in command():
print("Hello there.")
This still did not work so I did both these again but used "if" instead of "for", and nothing had changed. If anyone could help, it would be much appreciated, thanks! - James.

You need to use in operator for membership checking:
if 'hi' in command:
print("Hello there.")
Also Note that since command is a string and not a callable object you can not use parenthesis the the trailing of it.
And note that when you use in it checks the membership in the whole of the string and it's possible that you have another word in your text which is contains hi like high, that using in it will returns True which is not what you want.
So all you should do is splitting the string with whitespaces and check the membership of word hi within other words:
if 'hi' in command.split():
print("Hello there.")

Related

How to output string with line breaks, and separate before the number? [Python]

Not sure if I clearly describe my question, my original string is:
"1.you are beautiful 2.hello world 3.Thanks!"
I want the output to be:
"1.you are beautiful"
"2.hello world"
"3.Thanks!"
or
"1.you are beautiful
2.hello world
3.Thanks!"
I used split() when the sentence contains comma or period. However, I am thinking if I can write a function by using the number. For example, if type(item)==int then add a line break
Thank you for your help!
Here you go. This will only work for single digit numbers and will work with or without the period.
a='1.you are beautiful 2.hello world 3.Thanks!'
out=''
for ch in a:
if ch.isdigit():
out+='\n'+ch
else:
out+=ch
print(out)
If you want to detect any length number (e.g. 11) you would have to use enumerate(a) and "look ahead" to find the period '.' with another for loop and then add the new line or look into use the re package and Regular Expressions.

Can I make Python check my list to see if user input contains strings in my list using if statements? If not are there any alternatives?

Beginner with Python but I wanted to use a list to contain multiple potential string responses that the user may give in the input.
def Front_Door():
print("Welcome to the Party Friend!")
Emotional_state = input("How are You Today? ")
Positive_Emotion = ["good", "fine", "happy"]
I tried to use an if statement to get python to check through my list to see if the input contained any of the strings listed in the e.g. I gave.
if Positive_Emotion in Emotional_state:
print("That's Great! Happy to have you here!")
The code still manages to prompt me for Emotional_state but it just repeats the question one more time, if I respond with one of then strings I've listed again it gives me this error:
if Positive_Emotion in Emotional_state:
TypeError: 'in <string>' requires string as left operand, not list
I'm guessing there is a method to make Python search through my list of strings and cross reference it with my inputs and give me the response I want?
Any help is appreciated :).
You are checking if the whole list is in the string!
What you probably want to do is check if any of the items in the list are in the string.
Something like:
if any( [emotion in Emotional_state for emotion in Positive_Emotion] ):
print("That's Great! Happy to have you here!")
This will check each emotion in the list, and if any of them are in the string it will return True.
Hope this helps.
I'm all too late to the party, but here are my two cents.
You only need Positive_Emotion and Emotional_state to switch places in your if statement, so that it becomes:
if Emotional_state in Positive_Emotion:
print("That's Great! Happy to have you here!")

Python-docx: Editing a pre-existing Run

import docx
doc = docx.Document('CLT.docx')
test = doc.paragraphs[12].runs[2].text
print(test)
doc.save(input('Name of docx file? Make sure to add file extension '))
I've trying to figure out some way to add/edit text to a pre-existing run using python-docx. I've tried test.clear() just to see if I can remove it, but that doesn't seem to work. Additionally, I tried test.add_run('test') and that didn't work either. I know how to add a new run but it will only add it at the end of the paragraph which doesn't help me much. Currently, 'print' will output the text i'd like to alter within the document, "TERMOFINTERNSHIP". Is there something i'm missing?
The text of a run can be edited in its entirety. So to replace "ac" with "abc" you just do something like this:
>>> run.text
"ac"
>>> run.text = "abc"
>>> run.text
"abc"
You cannot simply insert characters at some location; you need to extract the text, edit that str value using Python str methods, and replace it entirely. In a way of thinking, the "editing" is done outside python-docx and you're simply using python-docx for the "before" and "after" versions.
But note that while this is quite true, it's not likely to benefit you much in the general case because runs break at seemingly random locations in a line. So there is no guarantee your search string will occur within a single run. You will need an algorithm that locates all the runs containing any part of the search string, and then allocate your edits accordingly across those runs.
An empty run is valid, so run.text == "" may be a help when there are extra bits in the middle somewhere. Also note that runs can be formatted differently, so if part of your search string is bold and part not, for example, your results may be different than you might want.

How to remove white spaces and capitalize every first letter in the string in the robotramework

How can I remove white spaces and capitalize every first letter in the string in the robotframework, so later I use the result in the Selenium library calls?
Test to Unlock the Service Account:
Open Browser ${URL} ${Browser}
${string_1} = get text ${question_1}
${temp_answer} = set variable ${string_1}.title()
${answer}= evaluate ${string_1}.replace(" ","")
Input Text ${Answer_1} ${answer}
sleep 5s
Input:
Legal business name
Output:
LegalBusinessName?
You were close to achieving it, but made two crucial mistakes. The first one is you used Set Variable and tried calling the python's title() string method in the argument - but that doesn't work for the keyword. It is a straightforward assignment - synonymous to the = operator; so what you ended up with as value was the string "Legal business name.title()". You should use the Evaluate keyword like in the second call, which does python's code eval.
The other mistake was to use two different variables - you store the capitalized version in the var ${temp_answer}, but then you don't remove the whitespace from it, but from the original one - ${string_1}. So even if the capitalization worked, you still wouldn't get the desired end result in the ${answer} var.
Here's a one-liner how to achieve what you need:
${answer}= evaluate """${string_1}""".title().replace(" ","")
The 2 methods are chained - replace() works on the result of title(), and the value of string_1 is in triple quotes so python works with its sting representation.

Compare a user input to a list python3

Hey guys so I tried looking at previous questions but they dont answer it like my teacher wants it to be answered. Basically i need to get a string from a user input and see if it has:
at least one of [!,#,#,$,%,^,&,*,(,)] (non-letter and nonnumeric
character)
o Create a list for these special characters
I have no idea how to make a def to do this. Please help!
You should probably look into Regular expressions. Regular expressions allow you to do many string operations in a concise way. Specifically, you'll want to use re.findall() in order to find all special characters in your string and return them. You can check if the returned list has length 0 to check if there were any special characters at all.
With regards to building the regular expression to find special characters itself... I'm sure you can figure that part out ;)
Please try the below
import re
inputstring = raw_input("Enter String: ")
print inputstring
print "Valid" if re.match("^[a-zA-Z0-9_]*$", inputstring) else "Invalid"

Resources