I want to know if there's way to do this:
printf("address is %x", address)
in Python. That is to integrate special strings that control the format of a output string. Thanks.
Just use the % operator. See the documentation for details.
address = 16
print "address is %x" % address
The modern and preferred1 way to perform string formatting operations is to use str.format:
print "address is {:x}".format(address)
Although the hex function works equally well in this case:
# [2:] removes the leading '0x'
print "address is", hex(address)[2:]
1For those who would like a citation, here is a note from the documentation for % formatting:
The formatting operations described here are obsolete and may go away
in future versions of Python. Use the new String Formatting in new
code.
Related
I've been looking around and I've been unable to find a definitive answer to this question: what's the recommended way to print variables in Python?
So far, I've seen three ways: using commas, using percent signs, or using plus signs:
>>> a = "hello"
>>> b = "world"
>>> print a, "to the", b
hello to the world
>>> print "%s to the %s" % (a, b)
hello to the world
>>> print a + " to the " + b
hello to the world
Each method seems to have its pros and cons.
Commas allow to write the variable directly and add spaces, as well as automatically perform a string conversion if needed. But I seem to remember that good coding practices say that it's best to separate your variables from your text.
Percent signs allow that, though they require to use a list when there's more than one variable, and you have to write the type of the variable (though it seems able to convert even if the variable type isn't the same, like trying to print a number with %s).
Plus signs seem to be the "worst" as they mix variables and text, and don't convert on the fly; though maybe it is necessary to have more control on your variable from time to time.
I've looked around and it seems some of those methods may be obsolete nowadays. Since they all seem to work and each have their pros and cons, I'm wondering: is there a recommended method, or do they all depend on the context?
Including the values from identifiers inside a string is called string formatting. You can handle string formatting in different ways with various pros and cons.
Using string concatenation (+)
Con: You must manually convert objects to strings
Pro: The objects appear where you want to place the into the string
Con: The final layout may not be clear due to breaking the string literal
Using template strings (i.e. $bash-style substitution):
Pro: You may be familiar with shell variable expansion
Pro: Conversion to string is done automatically
Pro: Final layout is clear.
Con: You cannot specify how to perform the conversion
Using %-style formatting:
Pro: similar to formatting with C's printf.
Pro: conversions are done for you
Pro: you can specify different type of conversions, with some options (e.g. precision for floats)
Pro: The final layout is clear
Pro: You can also specify the name of the elements to substitute as in: %(name)s.
Con: You cannot customize handling of format specifiers.
Con: There are some corner cases that can puzzle you. To avoid them you should always use either tuple or dict as argument.
Using str.format:
All the pros of %-style formatting (except that it is not similar to printf)
Similar to .NET String.Format
Pro: You can manually specify numbered fields which allows you to use a positional argument multiple times
Pro: More options in the format specifiers
Pro: You can customize the formatting specifiers in custom types
The commas do not do string-formatting. They are part of the print statement statement syntax.
They have a softspace "feature" which is gone in python3 since print is a function now:
>>> print 'something\t', 'other'
something other
>>> print 'something\tother'
something other
Note how the above outputs are exactly equivalent even though the first one used comma.
This is because the comma doesn't introduce whitespace in certain situations (e.g. right after a tab or a newline).
In python3 this doesn't happen:
>>> print('something\t', 'other')
something other
>>> print('something\tother') # note the difference in spacing.
something other
Since python2.6 the preferred way of doing string formatting is using the str.format method. It was meant to replace the %-style formatting, even though currently there are no plans (and I don't there will ever be) to remove %-style formatting.
string.format() basics
Here are a couple of example of basic string substitution, the {} is the placeholder for the substituted variables. If no format is specified, it will insert and format as a string.
s1 = "so much depends upon {}".format("a red wheel barrow")
s2 = "glazed with {} water beside the {} chickens".format("rain", "white")
You can also use the numeric position of the variables and change them in the strings, this gives some flexibility when doing the formatting, if you made a mistake in the order you can easily correct without shuffling all variables around.
s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
The format() function offers a fair amount of additional features and capabilities, here are a few useful tips and tricks using .format()
Named Arguments
You can use the new string format as a templating engine and use named arguments, instead of requiring a strict order.
madlib = " I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table")
>>> I took the cheese off the table
Reuse Same Variable Multiple Times
Using the % formatter, requires a strict ordering of variables, the .format() method allows you to put them in any order as we saw above in the basics, but also allows for reuse.
str = "Oh {0}, {0}! wherefore art thou {0}?".format("Romeo")
>>> Oh Romeo, Romeo! wherefore art thou Romeo?
Use Format as a Function
You can use .format as a function which allows for some separation of text and formatting from code. For example at the beginning of your program you could include all your formats and then use later. This also could be a nice way to handle internationalization which not only requires different text but often requires different formats for numbers.
email_f = "Your email address was {email}".format
print(email_f(email="bob#example.com"))
Escaping Braces
If you need to use braces when using str.format(), just double up
print(" The {} set is often represented as {{0}} ".format("empty"))
>>> The empty set is often represented as {0}
the question is, wether you want print variables (case 1) or want to output formatted text (case 2). Case one is good and easy to use, mostly for debug output.
If you like to say something in a defined way, formatting is the better choice. '+' is not the pythonic way of string maipulation.
An alternative to % is "{0} to the {1}".format(a,b) and is the preferred way of formatting since Python 3.
Depends a bit on which version.
Python 2 will be simply:
print 'string'
print 345
print 'string'+(str(345))
print ''
Python 3 requires parentheses (wish it didn't personally)
print ('string')
print (345)
print ('string'+(str(345))
Also the most foolproof method to do it is to convert everything into a variable:
a = 'string'
b = 345
c = str(345)
d = a + c
I know of two ways to format a string:
print 'Hi {}'.format(name)
print 'Hi %s' % name
What are the relative dis/advantages of using either?
I also know both can efficiently handle multiple parameters like
print 'Hi %s you have %d cars' % (name, num_cars)
and
print 'Hi {0} and {1}'.format('Nick', 'Joe')
There is not really any difference between the two string formatting solutions.
{} is usually referred to as "new-style" and %s is "old string formatting", but old style formatting isn't going away any time soon.
The new style formatting isn't supported everywhere yet though:
logger.debug("Message %s", 123) # Works
logger.debug("Message {}", 123) # Does not work.
Nevertheless, I'd recommend using .format. It's more feature-complete, but there is not a huge difference anyway.
It's mostly a question of personal taste.
I use the "old-style" so I can recursively build strings with strings. Consider...
'%s%s%s'
...this represents any possible string combination you can have. When I'm building an output string of N size inputs, the above lets me recursively go down each root and return up.
An example usage is my Search Query testing (Quality Assurance). Starting with %s I can make any possible query.
/.02
I have a floating point number, say 135.12345678910. I want to concatenate that value to a string, but only want 135.123456789. With print, I can easily do this by doing something like:
print "%.9f" % numvar
with numvar being my original number. Is there an easy way to do this?
With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.
# Option one
older_method_string = "%.9f" % numvar
# Option two
newer_method_string = "{:.9f}".format(numvar)
But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has info on the various flags.
Python 3.6 (officially released in December of 2016), added the f string literal, see more information here, which extends the str.format method (use of curly braces such that f"{numvar:.9f}" solves the original problem), that is,
# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
solves the problem. Check out #Or-Duan's answer for more info, but this method is fast.
Python 3.6
Just to make it clear, you can use f-string formatting. This has almost the same syntax as the format method, but make it a bit nicer.
Example:
print(f'{numvar:.9f}')
More reading about the new f string:
What's new in Python 3.6 (same link as above)
PEP official documentation
Python official documentation
Really good blog post - talks about performance too
Here is a diagram of the execution times of the various tested methods (from last link above):
Using round:
>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
In case the precision is not known until runtime, this other formatting option is useful:
>>> n = 9
>>> '%.*f' % (n, numvar)
'135.123456789'
It's not print that does the formatting, It's a property of strings, so you can just use
newstring = "%.9f" % numvar
To set precision with 9 digits, get:
print "%.9f" % numvar
Return precision with 2 digits:
print "%.2f" % numvar
Return precision with 2 digits and float converted value:
numvar = 4.2345
print float("%.2f" % numvar)
The str function has a bug. Please try the following. You will see '0,196553' but the right output is '0,196554'. Because the str function's default value is ROUND_HALF_UP.
>>> value=0.196553500000
>>> str("%f" % value).replace(".", ",")
I'm just starting to fool around with formatting the output of a print statement.
The examples I've seen have a % after the format list and before the arguments, like this:
>>> a=123
>>> print "%d" % a
123
What is the meaning of the % and more important, why is it necessary?
It's the string formatting operator, it tells Python to look at the string to the left, and build a new string where %-sequences in the string are replaced with formatted versions of the values from the right-hand side of the operator.
It's not "necessary", you can print values directly:
>>> print a
123
But it's nice to have printf()-style formatting available, and this is how you do it in Python.
As pointed out in a comment, note that the string formatting operator is not connected to print in any way, it's an operator just like any other. You can format a value into a string without printing it:
>>> a = 123
>>> padded = "%05d" % a
>>> padded
00123
In python the % operator is implemented by calling the method __mod__ on the left hand argument, falling back to __rmod__ on the right argument if it's not found. So what you have written is equivalent to
a = 123
print "%d".__mod__(a)
Python's string classes simply implement __mod__ to do string formatting.
Also note that this style of string formatting is referred to in the documentation as "old string formatting"; moving forward we should move to the new-style string formatting as described here: http://docs.python.org/library/stdtypes.html#str.format
like:
>>> a=123
>>> print "{0}".format(a)
123
See Format String Syntax for a description of the various
formatting options that can be specified in format strings.
This method of string formatting is the new standard in Python 3.0,
and should be preferred to the % formatting described in String
Formatting Operations in new code.
I know it's a really simple question, but I have no idea how to google it.
how can I do
print '%s' % (my_url)
So that my_url is used twice? I assume I have to "name" the %s and then use a dict in the params, but I'm not sure of the proper syntax?
just FYI, I'm aware I can just use my_url twice in the params, but that's not the point :)
print '%(url)s' % {'url': my_url}
In Python 2.6+ and Python 3, you might choose to use the newer string formatting method.
print('{0}'.format(my_url))
which saves you from repeating the argument, or
print('{url}'.format(url=my_url))
if you want named parameters.
print('{}'.format(my_url, my_url))
which is strictly positional, and only comes with the caveat that format() arguments follow Python rules where unnamed args must come first, followed by named arguments, followed by *args (a sequence like list or tuple) and then *kwargs (a dict keyed with strings if you know what's good for you).
The interpolation points are determined first by substituting the named values at their labels, and then positional from what's left.
So, you can also do this...
print('{}'.format(my_url, my_url, not_my_url=her_url))
But not this...
print('{}'.format(my_url, not_my_url=her_url, my_url))
Solution in Python 3.6+
Python 3.6 introduces literal string formatting, so that you can format the named parameters without any repeating any of your named parameters outside the string:
print(f'{my_url:s}')
This will evaluate my_url, so if it's not defined you will get a NameError. In fact, instead of my_url, you can write an arbitrary Python expression, as long as it evaluates to a string (because of the :s formatting code). If you want a string representation for the result of an expression that might not be a string, replace :s by !s, just like with regular, pre-literal string formatting.
For details on literal string formatting, see PEP 498, where it was first introduced.
You will be addicted to syntax.
Also C# 6.0, EcmaScript developers has also familier this syntax.
In [1]: print '{firstname} {lastname}'.format(firstname='Mehmet', lastname='Ağa')
Mehmet Ağa
In [2]: print '{firstname} {lastname}'.format(**dict(firstname='Mehmet', lastname='Ağa'))
Mehmet Ağa
For building HTML pages, you want to use a templating engine, not simple string interpolation.
Another option is to use format_map:
print('{s}'.format_map({'s': 'my_url'}))
As well as the dictionary way, it may be useful to know the following format:
print '%s' % (my_url, my_url)
Here it's a tad redundant, and the dictionary way is certainly less error prone when modifying the code, but it's still possible to use tuples for multiple insertions. The first %s is substituted for the first element in the tuple, the second %s is substituted for the second element in the tuple, and so on for each element in the tuple.
I recommend this syntax
dictionary_of_string_values = {
"my_text" : "go to w3schools",
"my_url" : "https://www.w3schools.com",
}
print ('{my_text}'.format(**dictionary_of_string_values))
It is very useful when you have to format a string with lots of placeholders.
You can also make it shorter like this:
print ('{my_text}'.format(
**{
"my_text" : "go to w3schools",
"my_url" : "https://www.w3schools.com",
}
)
)