1

For example, if I'm just printing out an error, is it better to do

print "Error encountered: " + error.args[0]

or

print ''.join("Error encountered: ", error.args[0])

or perhaps

print "Error encountered: {0}".format(error.args[0])

Which one would be the fastest, and which would be the most "Pythonic" way to do it?

1
  • For "fastest", you need to just try it. I suspect it'll be quite close and may even depend on the particular implementation Commented Jul 8, 2013 at 4:20

3 Answers 3

4

This is generally the best way

print "Error encountered: {0}".format(error.args[0])

When you need to internationalise you application, you can often just go

print _("Error encountered: {0}").format(error.args[0])

And let gettext to the rest of the work

If there are multiple argumnent's it's best to use the mapping version

print _("Error encountered: {err}").format(err=error.args[0])

So it'll still work if a translation needs to move the order of the arguments around

Sign up to request clarification or add additional context in comments.

Comments

2

No need to concatenate strings. Just print them.

print "Error encountered:", error.args[0]

1 Comment

@ron975: Note that the print statement prints a space between consecutive arguments. This is not always what you want.
0

You could concatenate two strings using several different techniques:

str1 = 'Hello'
str2 = 'there!'

print (str1, str2)

The use of the comma between variables in a print statement automatically inserts a space between the items that are output. If you had used a plus sign, i.e., print (str1 + str2), the above output would look like 'HelloWorld'.

Hope this helps.

Caitlin

4 Comments

The OP is using Python2 - we can tell since print is being used as a statement. This is the Python3 version of @falsetru's answer
Ah, yes. I noticed that. Wouldn't the syntax I used apply to Python 2 as well though?
Just try it. You'll see that it prints the 2-tuple instead of just the two strings.
You can use from __future__ import print_function though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.