kesh
kesh

Reputation: 21

How do you add extra string in after a variable?

k=int(input("enter a number"))

for i in range (1,11):
result = i * k
print (i, "x", k + "is" , result) 

if i take out the "is" it shows this:

    1 x 7 7 
    2 x 7 14
    3 x 7 21
    4 x 7 28
    5 x 7 35
    6 x 7 42
    7 x 7 49
    8 x 7 56
    9 x 7 63
    10 x 7 70

when i add the "is" it shows this:

 enter a number7
   Traceback (most recent call last):
  File "C:/Windows/System32/cool.py", line 7, in <module>
    print (i, "x", k + "is" , result)
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

but i want it to look like:

 1 x 7 is 7...

Upvotes: 0

Views: 61

Answers (2)

Henrik Andersson
Henrik Andersson

Reputation: 47172

You cannot concatenate a string with a number as you do when you do k + "is".

Either convert k to a string by using the str function or use string formatting instead which is better and safer to use

print "{0} x {1} is {2}".format(i, k, result)

or if you want to name your variables

print "{i} x {k} is {result}".format(i=i, k=k, result=result)

Upvotes: 2

Martin Konecny
Martin Konecny

Reputation: 59591

Your problem is this part:

k + "is"

You cannot add a string and integer together. Try writing a simple program with 5 + "X" and you will see the same issue. To resolve this, make sure you convert your integer to a string, before adding to another string.

print (i, "x", str(k) + "is" , result)

Upvotes: 0

Related Questions