chyyran
chyyran

Reputation: 2656

Best way to concatenate short strings in Python

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?

Upvotes: 1

Views: 551

Answers (3)

CaitlinG
CaitlinG

Reputation: 2015

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

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304473

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

Upvotes: 4

falsetru
falsetru

Reputation: 369454

No need to concatenate strings. Just print them.

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

Upvotes: 2

Related Questions