what does this mean:
print "{0} ({1})"
in this code:
for x in [None,3,4.5,"foo",lambda : "moo",object,object()]:
print "{0} ({1})".format(x,type(x))
As mentioned in the comments, they are placeholders for your string, here is a bit of an explanation with some examples. Also mentioned, is the documentation here, which explains this very well.
When you provide the arguments for your format method, the values of these arguments will be set in these placeholders. The order in which the arguments will be used, depends on how you write these placeholders. You can actually even have empty placeholders "{}", which will just take the arguments in order.
Observe the following examples.
Assuming the following two arguments are set:
arg1 = "pretzels"
arg2 = "thirsty"
In order placeholders:
print("These {0} are making me {1}".format(arg1, arg2))
Outputs:
These pretzels are making me thirsty
Out of order placeholders:
print("These {1} are making me {0}".format(arg1, arg2))
Outputs:
These thirsty are making me pretzels
No value provided in placeholders:
print("These {} are making me {}".format(arg1, arg2))
Output:
These pretzels are making me thirsty
Related
So, I have the following function which should resemble the already implemented " print " function in Python. ( I know it is silly to make a function that only uses a pre-defined function but I am practicing with different things ) The thing that I want to do with my function is: make it act the same as the pre-defined one. That is, when the print function is called with no parameters, I would like it to print an empty line just as " print() " does. How do i do that ?
def print_str( string, how_many_times, tail ):
print ( string * how_many_times, end = tail )
print doesn't take a single string, it takes 0 or most strings as argument. end has a reasonable default. You can imagine a (simplified) definition of
def print(*args, end='\n'):
...
You need to do the same for yours. A reasonable default for how_many_times would be 1. If you don't want print_str to take multiple arguments, "" would be a reasonable default for string.
def print_str(string="", how_many_times=1, tail='\n'):
print(string * how_many_times, end=tail)
You can do something like this:
def myfunc(a=None):
if a == None:
print()
else:
print("hi")
If no arguments are presented it prints nothing, but if an argument is given it prints 'hi'.
I have seen loads of answers that say to use {} or str() + to make the input() only get given 1 argument.
But what parts of the input need to go with those? This is my code
name.append(input("What is their name"))
score.append(input("What did", name[x], "score"))
I'm pretty sure the 3 arguments are the "what did", "name[]x" and "score"
How would I make these one argument while keeping the same order and meaning?
You can format the string so that you only pass 1 argument:
score.append(input("What did %s score" % name[x]))
However if you want to add multiple arguments do this:
score.append(input("%s scored %d points!" % (name[x], points)))
You are adding three arguments in total while the function expects only one so pass one argument only:
name.append(input("What is their name"))
score.append(input("What did %s score" % name[x]))
The % syntax is the old syntax. Try to learn the new syntax as well
score.append(input("What did {} score".format(name[x])))
This website has some good breakdowns of common usages between the old and the new: https://pyformat.info/
Here is my problem I have a number of functions defined and I want to loop through a list of these functions and run them one at a time in the correct order.
def one():
print "One "
def two():
print "Two "
def three(): "Three "
print "Three "
arr = ('one','two','three')
for fnc in arr:
<some how run the function name in the variable fnc>
Any Help Appreciated, as I am a beginner with python and django.
Python functions are first order objects; just put them in the sequence:
arr = (one, two, three)
for fnc in arr:
fnc()
You could store strings too, but then you need to turn those back into the function object first. That'd just be extra busywork you don't really need to do.
You can still turn strings into objects; the globals() function gives you the current global namespace as a dictionary, so globals()['one'] gives you the object referenced by the name one, but this would also give you access to every global in your module; if you then made a mistake it could lead to hard to track bugs or even security holes (as end-users could potentially abuse functions you didn't intent to be called).
If you really need to map names to functions, because, say, you need to take input from something else that only produces strings, use a predefined dictionary:
functions = {
'one': one,
'two': two,
'three': three,
}
and map your string to the function:
function_to_call = 'one'
functions[function_to_call]()
Your function names do not need to match the string values here. By using a dedicated dictionary you limit what can be called.
It depends on where the functions are defined, but if they are in the current context, you can get a reference to them by retrieving them from the globals function:
def fn():
return ":)"
for f in['fn']:
print globals()[f]()
Seems to work...
method_name = 'one'
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise Exception("Method %s not implemented" % method_name)
returned_value = method()
For your specific example, simply use eval:
arr = ('one','two','three')
for fnc in arr:
eval(fnc + '()')
Be aware that using eval() is considered bad practice by some.
I'm making a socket client and need to define a function which sends the following kind of message to server: sometext,[name_1],[name_2],...,[name_n]. Actually the message is more complex, but for the sake of an example I simplified it.
Where:
... - represents the rest of the names (comma delimited) between name_2 and the last name_n
there could be arbitrary number of names each time
I know there are *args and **kwargs, but how to correctly use them in this case with str.format()? I need something like this:
def send_names(*args):
print('sometext,{*args},'.format(*args)) # as an example we just print
I know this code doesn't work because {*args} is illegal here.
The code works when I know the number of *args beforehand, like in here:
def send_names(*args):
print('sometext,{0},{1},{2}'.format(*args)) # as an example we just print
What am I missing?
You can join the *args to accomplish what you want:
def send_names(*args):
print('sometext, {0}'.format(', '.join(args)))
send_names('message1', 'message2', 'message3')
result:
sometext, message1, message2, message3
You cannot use *args or **kwargs to apply to a variable number of slots, no. You'd have to create the slots yourself based on the length:
','.join(['{}'] * len(args)).format(*args)
You can then interpolate the result of that into another template as needed. The above works with any type of argument normally accepted by a formatting slot.
Demo:
>>> args = ('foo', 'bar')
>>> ','.join(['{}'] * len(args)).format(*args)
'foo,bar'
>>> args = ('foo', 'bar', 'baz')
>>> ','.join(['{}'] * len(args)).format(*args)
'foo,bar,baz'
>>> args = (1, 2, 3)
>>> ','.join(['{}'] * len(args)).format(*args)
'1,2,3'
I think you should avoid using .format and just ', '.join the args as needed. You didn't mention any specific reason why you need to .format the strings in the question. Just like the solution by #Selcuk
I have the following function which takes 4 arguments (we don't know which are set and which aren't before runtime).
myFuct(self, arg1, arg2, arg3, arg4):
# db insert function for only those args that are set
Is there an efficient way of unraveling the set arguments in a mysql database with a single sql query?
P.S. I am looking for a pythonic way to do this without having to say if-this-then-that for a million times...
Thanks in advance.
Not entirely sure what you need.
def myfunc(*args, **kwargs):
...
Can take any number of arguments, is this what you're looking for?
print(*(1,2,3,4)) * "unravels" the arguments in the order they are given but can be passed as one object or any number of objects.
However, passing these into a SQL statement without knowing the precise length of the arguments. Since SQL to my knowledge is a bit strict on how you pass the arguments.
You could do something like:
def myfunc(*args):
statement = "INSERT INTO table VALUES(" + ', '.join(str(x) for x in args) + ");"
db.execute(statement)
Note of course that this can only be used if you actually pass arguments to myfunc that are of the correct type, order and length.
in postgresql you have something called a prepared statement which would come in handy here.
def myfunc(*args):
statement = "INSERT INTO table VALUES(" + ', '.join('$'+str(i) for i in range(0, len(args)+1)) + ");"
handle = db.prepare(statement)
handle(args)
Where you simply define $1, $2 and so on in the prepared statement and then pass the equivilant number of arguments to the handler which will execute the query with the correct format on each of the values enabling you to pass integers, strings and arrays.. any way you like :)
Also, if the argument is a dictionary (mentioned in a comment)...
You'd have to do:
def myfunc(*args):
keys = ', '.join(str(x) for x in list(args.keys()))
values = ', '.join(str(val) for k, val in list(args.items()))
statement = "INSERT INTO table (" + keys + ") VALUES(" + values + ");"
db.execute(statement)
Again, assumes the dictionary is passed with proper variables for a execution to proceed.
You can use variable-length argument list construct:
def myfunc(*args):
args_non_empty = [a for a in args if a]
This allows you to pass any number of argument to your method. You can easily then filter them by traversing the list.