erlang
erlang

Reputation: 27

Using a variable as both an integer and a string (Python)

I would like to use a variable as an integer and a string in the same statement. In BASIC, it would look like this:

cnt = 0

while cnt < 10:
    cnt = cnt + 1
    print cnt + " + 1 = " + cnt + 1 

I understand it's a bit different with Python (integers have to be converted before you print them as strings, but here using a function such as "cnt = str(cnt)" doesn't seem to work very well). What would be the easy way to do this?

Upvotes: 0

Views: 3469

Answers (6)

Marcelo Cantos
Marcelo Cantos

Reputation: 185922

For Python 2.6+, the format method is the preferred way to build up strings containing other values:

'{0} + 1 = {1}'.format(cnt, cnt + 1)

Upvotes: 5

RoundTower
RoundTower

Reputation: 909

You can print ints as well as strings. You may be confused by some of the answers if you know that it is quite possible to write print cnt on its own, without explicitly putting it into a string.

The string formatting language is useful and powerful and something you do need to know about. But it's perfectly fine to write

print cnt, "+ 1 =", cnt + 1

which is closer in spirit to what you asked. Python automatically adds spaces between the arguments, and a newline character at the end of the line (to suppress this, add another comma at the end).

Upvotes: 1

agf
agf

Reputation: 176850

cnt = 0

while cnt < 10:
    print str(cnt) + " + 1 = " + str(cnt + 1)
    cnt = cnt + 1

or

for cnt in range(10):
    print str(cnt) + " + 1 = " + str(cnt + 1)

or

for cnt in range(10):
    print "%d + 1 = %d".format(cnt, cnt + 1)

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96266

print str(cnt) + " + 1 = " + str(cnt + 1)

or

print "%d + 1 = %d" % (cnt, cnt+1)

Upvotes: 1

Mark Rushakoff
Mark Rushakoff

Reputation: 258298

You had it nearly right; you just need to tell Python exactly when to make something a string.

>>> cnt = 0
>>> while cnt < 10:
...     cnt += 1
...     print str(cnt) + " + 1 = " + str(cnt + 1)
... 
1 + 1 = 2
2 + 1 = 3
3 + 1 = 4
4 + 1 = 5
5 + 1 = 6
6 + 1 = 7
7 + 1 = 8
8 + 1 = 9
9 + 1 = 10
10 + 1 = 11

Strictly speaking, you aren't treating cnt as both an integer and a string here -- it's always an integer.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798884

There isn't one, since Python is strongly typed.

print '%d + 1 = %d' % (cnt, cnt + 1)

Upvotes: 6

Related Questions