I looked at the following few posts and wasn't quite able to figure out what I want to do.
python - How to format variable number of arguments into a string?
Pass *args to string.format in Python?
What I want to do is simple. Given some array of variable length I want to be able to print all the arguments individually. That is, I want
print('{} {} ...'.format(*arg))
Obviously I won't be able to predict how many {} I will need before hand and I tried len(x)*'{}' which didn't yield what I wanted. If I leave that out then I only get the first argument. What is the way to achieve this?
so why not just:
print(" ".join(map(str,args)))
which does the same thing as {} {} ... in format
Why use a format string at all? print can do this for you:
print(*arg)
I wondered whether it is possible to print (for example a string) in Python without the print function. This can be done by a command or by some trick.
For example, in C there are printf and puts.
Can someone show me a way to print or to deny this possibility?
sys.stdout.write("hello world\n")
import sys
sys.stdout.write("hello")
You can use
sys.stdout.write()
Sometimes I find sys.stdout.write more convenient than print for printing many things to a single line, as I find the ending comma syntax of print for suppressing the newline inconvenient.
What I am looking to do is output the contents of the print list as above at the end of the sys.stdout.write just after the ScriptRes:OK:
My code
print list[0]['VersionString']
sys.stdout.write("ScriptRes:OK:")
I am sure this is probably easy to do but my googling is drawing blanks!
The question is hard to understand, but it sounds like you want the result of the first print right after OK:.
No idea why you mix print and sys.stdout.write (which, as a beginner, you should probably not do unless you know why).
So one obvious way is print "ScriptRes:OK:", list[0]['VersionString']
I suppose you have a dictionary inside a list ,try this
sys.stdout.write('ScriptRes:OK:%s' %list[0]['VersionString'])
I'm reading into a csv file an extracting a piece of data with the line:
x = float(node[1])
when I print(x), I get the correct value or the exact value found in the cell. e.g 153.018848
But when I try to pass x as variable in the following:
print('<node version="0" lon="%d">' %(x))
the output will be <node version="0" lon="153"> . Of course I want the value 153.018848.
What have I overlooked?
Thanks in advance.
You've overlooked the fact that %d is for integers. Try %f instead.
You're using the wrong format flag. %d is for integers, use %f for floats.
You want to replace your %d with %f, problem solved ;)
See: http://docs.python.org/release/2.5.2/lib/typesseq-strings.html
For bonus points, are you aware you can put together long format strings that are still readable using dictionaries? You can read more about it, but the !r option I have used with call the repr() function on the variable, so you know what is inserted will be exactly what you've seen printed in your debugging:
string = """<tagname id=%{idval!r} type=%{tagtype!r} foo=%{bar!r}"""
print string.format( **{'idval':var1, 'tagtype':var2, 'bar':var3})
I was going through http://web2py.com/book/default/chapter/02 and found this:
>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
number is 3
It has been given that The last notation is more explicit and less error prone, and is to be preferred.
I am wondering what is the advantage of using the last notation.. will it not have a performance overhead?
>>> print 'number is ' + str(3)
number is 3
This is definitely the worst solution and might cause you problems if you do the beginner mistake "Value of obj: " + obj where obj is not a string or unicode object. For many concatenations, it's not readable at all - it's similar to something like echo "<p>Hello ".$username."!</p>"; in PHP (this can get arbitrarily ugly).
print 'number is %s' % (3)
number is 3
Now that is much better. Instead of a hard-to-read concatenation, you see the output format immediately. Coming back to the beginner mistake of outputting values, you can do print "Value of obj: %r" % obj, for example. I personally prefer this in most cases. But note that you cannot use it in gettext-translated strings if you have multiple format specifiers because the order might change in other languages.
As you forgot to mention it here, you can also use the new string formatting method which is similar:
>>> "number is {0}".format(3)
'number is 3'
Next, dict lookup:
>>> print 'number is %(number)s' % dict(number=3)
number is 3
As said before, gettext-translated strings might change the order of positional format specifiers, so this option is the best when working with translations. The performance drop should be negligible - if your program is not all about formatting strings.
As with the positional formatting, you can also do it in the new style:
>>> "number is {number}".format(number=3)
'number is 3'
It's hard to tell which one to take. I recommend you to use positional arguments with the % notation for simple strings and dict lookup formatting for translated strings.
I can think of a few differences.
First to me is cumbersome, if more than one variable is involved. I can not speak of performance penalty on that. See additional arguments below.
The second example is positional dependent and it can be easy to change position causing errors. It also does not tell you anything about the variables.
The third example, the position of variables is not important. You use a dictionary. This makes it elegant as it does not rely on positional structuring of variables.
See the example below:
>>> print 'number is %s %s' % (3,4)
number is 3 4
>>> print 'number is %s %s' % (4,3)
number is 4 3
>>> print 'number is %(number)s %(two)s' % dict(number=3, two=4)
number is 3 4
>>> print 'number is %(number)s %(two)s' % dict(two=4, number=3)
number is 3 4
>>>
Also another part of discussion on this
"+" is the string concatenation operator.
"%" is string formatting.
In this trivial case, string formatting accomplishes the same result as concatenation. Unlike string formatting, string concatenation only works when everything is already a string. So if you miss to convert your variables to string, concatenation will cause error.
[Edit: My answer was biased towards templating since the question came from web2py where templates are so commonly involved]
As Ryan says below, the concatenation is faster than formatting.
Suggestion is
Use the first form - concatenation, if you are concatenating just two strings
Use the second form, if there are few variables. You can invariably see the positions and deal with them
Use the third form when you are doing templating i.e. formatting a large piece of string with variable data. The dictionary form helps in providing meaning to variables inside the large piece of text.
I am wondering what is the advantage
of using the last notation..
Hm, as you said, the last notation is really more explicit and actually is less error prone.
will it not have a performance
overhead?
It will have little performance overhead, but it's minor if compared with data fetching from DB or network connections.
It's a bad, unjustified piece of advice.
The third method is cumbersome, violates DRY, and error prone, except if:
You are writing a framework which don't have control over the format string. For example, logging module, web2py, or gettext.
The format string is extremely long.
The format string is read from a file from a config file.
The problem with the third method should be obvious when you consider that foo appears three times in this code: "%(foo)s" % dict(foo=foo). This is error prone. Most programs should not use the third method, unless they know they need to.
The second method is the simplest method, and is what you generally use in most programs. It is best used when the format string is immediate, e.g. 'values: %s %s %s' % (a, b, c) instead of taken from a variable, e.g. fmt % (a, b, c).
The first concatenation is almost never useful, except perhaps if you're building list by loops:
s = ''
for x in l:
s += str(x)
however, in that case, it's generally better and faster to use str.join():
s = ''.join(str(x) for x in l)