user3342048
user3342048

Reputation: 55

How can I concatenate words and integers in python?

I am trying to get the coordinates for something, in the form "[x,y]". For one line, all of the y-values are 5, and the x-values are 50, 55, 60, etc. I am trying to get python to print the coordinates. I've gotten everything but the printing part -

for i in range(50,150):
    if (i%5 == 0):
        print '[' + int(i) + ',' + '5]';

I'm doing something wrong in the last line. Can you help me please?

Upvotes: 1

Views: 84

Answers (2)

user2357112
user2357112

Reputation: 280426

You need a string. Don't call int on your integer; call str, to get a string representation of it:

print '[' + str(i) + ',' + '5]'

or let the string format method take care of type coercion for you:

print '[{0},5]'.format(i)

or just make a list and print that. It'll have a space you weren't printing, which may or may not be what you want:

print [i, 5]

Upvotes: 3

mikedugan
mikedugan

Reputation: 2393

Python doesn't automatically perform the conversions. You need to convert your numbers using str() and then print.

for i in range(50,150):
  if(i%5 == 0):
    print '[' + str(i) + ',' + '5]';

Upvotes: 0

Related Questions