I am making a discord bot using python.
I have a function
def search(userName):
# ...
but the userName MAY contain spaces
Eg.
Enter userName: Me Head
and I want the function to read bot arguments given and join them together so it forms "MeHead"
Currently if I try to run my search(userName) function with two inputs it will just take the first input so
Enter userName: Me Head
will just run search("Me") and ignore anything after that first input
The input is received is a string, so it does not matter if there are or no spaces. To remove spaces, you must use the function:
str.replace(" ", "")
Related
I'm trying to format a user input into variables. I'm a novice to most advanced functions in python, but here's an example prompt:
userInput = input("Enter your four-character list:")
The user is supposed to enter three or four characters, a mix of letters and numbers. I would like to slice up the input into variables that can be plugged into other functions. For example, if the user input is "4 5 s t," I would like each of the four characters to be a variable. Spacing also shouldn't matter, whether it's at least one or five between each.
You can use the split method of strings in python
my_args = userInput.split()
This will return a python list of the input elements regardless of how many spaces there are.
Then you can work with your list like this
for arg in my_args:
#do something
I'm making a small github script for myself. I'm trying to have the call command with an argument then raw input as another argument. I have no idea how to even start.
file = raw_input("enter file name: ")
call(["command", "argument", "input here"])
How do i add the incorporate the raw input?
You can do this:
file_name = raw_input("enter file name: ")
call(["command", "argument", file_name])
Please don't use file as variable, it's a python type
And you don't need quotes, because file_name will be a string that you can put directly in your list.
You seem to confuse strings with string-literals. The first one is a sequence of characters (actually strings again in Python), whereas the latter is a way to write such a string within a program.
So
foo = "my string"
does not contain any actual quotes. E.g. the length is 9, the first character foo[0] is m and so forth.
raw_input returns a string-object, so if it's content should be passed on, you can just take the variable you assigned it to & and pass it as argument to create a list that in turn you pass to subprocess:
user_input = raw_input()
subprocess.check_call(["program", user_input])
For your actual use-case, don't be confused by having to use quotes in the shell for certain use-cases, as these serve a similar purpose there. The shell tokenizes input by spaces, so
$ command arg1 arg2 arg3
will be 3 arguments for command. But if you need one argument to contain spaces (e.g. certain filenames with spaces in them), you need to do
$ command "my spaceful argument"
However, the Python subprocess module (unless you use shell=True) does not suffer from this problem: there the arguments you pass as list will immediately be passed to the child-process without the need for quotes.
A simple solution is to just put your raw_input into your call:
call(["command", "argument", raw_input("enter file name: ")])
My script asks for user interaction and asks for his/her name. I am using raw_input to exhibit this functionality.
I want to check whether user gave any input or not.
I thought to check the entered string with a blank.
Currently the code looks like this :
str = raw_input("Enter your name: ")
if("" in str):
print "user din't entered anything"
The above code works partially and if user presses enter without any input, the output user din't entered anything is printed.
The issue is that the above code also works when user enters something like foo bar [Notice the space between foo and bar. Yes I know why this is happening.
Another alternative is to check the length of string entered. If user does not enter anything then length would be zero. But same issue arises here. What if user enters more than one blank ! The length logic will fail.
What shall I do to check whether user inputted any string or left it blank ?
Is there anything for string in python where I can do if(str == "")
Any help appreciated.
value = raw_input("Enter your name: ")
if not value.strip():
print "user din't entered anything"
strip() removes the trailling blank spaces and between word . if it is empty spaces . it remove all
isspace() checks if the string is just spaces without needing to create a new string object as strip() would
if(not str or str.isspace()):
print "user din't entered anything"
Aside: str is a builtin. Shadowing it with your own variables can cause interesting bugs
I want to know how to allow multiple inputs in Python.
Ex: If a message is "!comment postid customcomment"
I want to be able to take that post ID, put that somewhere, and then the customcomment, and put that somewhere else.
Here's my code:
import fb
token="access_token_here"
facebook=fb.graph.api(token)
#__________ Later on in the code: __________
elif msg.startswith('!comment '):
postid = msg.replace('!comment ','',1)
send('Commenting...')
facebook.publish(cat="comments", id=postid, message="customcomment")
send('Commented!')
I can't seem to figure it out.
Thank you in advanced.
I can't quite tell what you are asking but it seems that this will do what you want.
Assuming that
msg = "!comment postid customcomment"
you can use the built-in string method split to turn the string into a list of strings, using " " as a separator and a maximum number of splits of 2:
msg_list=msg.split(" ",2)
the zeroth index will contain "!comment" so you can ignore it
postid=msg_list[1] or postid=int(msg_list[1]) if you need a numerical input
message = msg_list[2]
If you don't limit split and just use the default behavior (ie msg_list=msg.split()), you would have to rejoin the rest of the strings separated by spaces. To do so you can use the built-in string method join which does just that:
message=" ".join(msg_list[2:])
and finally
facebook.publish(cat="comments", id=postid, message=message)
I want to wrap the colour input in quotes within python:
def main():
colour = input("please enter a colour")
So if I enter red into the input box it automatically makes it "red"
I'm not sure how to do this, would it be something along the lines of:
def main():
colour = """ + input("please enter a colour") + """
Kind regards
The issue is that this doesn't pass syntactically, as Python thinks the second " is the end of the string (the syntax highlighting in your post shows how it's being interpreted). The nicest to read solution is to use single quotes for the string: '"'.
Alternatively, you can escape characters (if you wish to, for example, use both types of quote in a string) with a backslash: "\""
A nice way of doing this kind of insertion of a value, rather than many concatenations of strings, is to use str.format:
colour = '"{}"'.format(input("please enter a colour"))
This can do a lot of things, but here, we are simply using it to insert the value we pass in where we put {}. (Note that pre-2.7, you will need to give the number of the argument to insert e.g: {0} in this case. Past that version, if you don't give one, Python will just use the next value).
Do note that in Python 2.x, you will want raw_input() rather than input() as in 2.x, the latter evaluates the input as Python, which could lead to bad things. In 3.x, the behaviour was fixed so that input() behaves as raw_input() did in 2.x.