How to avoid converting an integer to string when concatenating

Question:

I know that in python, you can’t simply do this:

number = 1
print "hello number " + number

you have to do this:

print "hello number " + str(number)

otherwise you’ll get an error.

My question is then, being python such a compact language and this feature of automatic casting/converting from integer to string available in so many other languages, isn’t there away to avoid having to use the str() function everytime? Some obscure import, or simply another way to do it?

Edit: When I say another way, I mean simpler more compact way to write it. So, I wouldn’t really consider format and alternative for instance.

Thanks.

Asked By: nunos

||

Answers:

You can avoid str():

print 'hello number {}'.format(number)

Anyway,

'abc' + 123

is equivalent to

'abc'.__add__(123)

and the __add__ method of strings accepts only strings.

Just like

123 + 'abc'

is equivalent to

(123).__add__('abc')

and the __add__ method of integers accept only numbers (int/float).

Answered By: eumiro

You can use string formatting, old:

print "hello number %s" % number

or new:

print "hello number {}".format(number)
Answered By: Pavel Anossov

As this answer explains, this will not happen in Python because it is strongly typed. This means that Python will not convert types that you do not explicitly say to convert.

Answered By: CoffeeRain

I tend to use the more compact format

>>> print "one",1,"two",2
one 1 two 2

Or, in python 3,

>>> print("one",1,"two",2)
one 1 two 2

Notice however that both options will always introduce a space between each argument, which makes it unsuitable for more complex output formatting, where you should use some of the other solutions presented.

Answered By: jgpaiva
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.