2

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.

nunos
  • 20,479
  • 50
  • 119
  • 154

4 Answers4

4

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).

eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 3
    While this is the right way to go for more complex cases, wouldn't `print "hello number", number` work equally well here? – DSM Mar 12 '13 at 15:21
  • @DSM - yes, it would. – eumiro Mar 12 '13 at 15:22
  • @DSM that's excatly the kind of answer I was looking for. Consider writing it as an answer so that I can accept it. Thanks. – nunos Mar 12 '13 at 16:04
4

You can use string formatting, old:

print "hello number %s" % number

or new:

print "hello number {}".format(number)
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • 1
    be aware that this calls str under the hood (I think at least) ... same with the other format string. just like "%d" will call int and %f will call float – Joran Beasley Mar 12 '13 at 15:25
2

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.

jgpaiva
  • 369
  • 2
  • 11
1

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.

Community
  • 1
  • 1
CoffeeRain
  • 4,460
  • 4
  • 31
  • 50