简体   繁体   中英

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?

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]

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]';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM