Hi
I am trying my first try at Python. I want to do something very similar to what sprintf does with C. I want to concatenate a string with a number and store it into a new string.

I wrote a snippet like this

username='user'
for i in range (1-100)
user=user_name+str(i)
print user
else: print 'The loop is done'

But this one fails to do the same. Can somene help me decipher where exactly I am going wrong.

Thanks for your help

regards
Ram

user_name = 'user'
for i in range ( 1, 100 ):
  user = user_name + str ( i )
  print user
else:
  print 'The loop is done'

If you want to do something even closer to sprintf(), you can use the formatting statement. As Narue pointed out, in Python you must use indentations to group your statements.

user_name = 'user'
for i in range ( 1, 100 ):
    #user = user_name + str ( i )
    user = "%s%d" % (user_name, i)
    print user
else:
    print 'The loop is done'

Note that the formatting code %s or %d etc. is the same as used in C for printf() or sprintf(). So if you use "%s%02d", you zero pad the numbers 1 to 9 and get strings like 'user01' and so on.

If you want to do something even closer to sprintf(), you can use the formatting statement. As Narue pointed out, in Python you must use indentations to group your statements.

user_name = 'user'
for i in range ( 1, 100 ):
    #user = user_name + str ( i )
    user = "%s%d" % (user_name, i)
    print user
else:
    print 'The loop is done'

Note that the formatting code %s or %d etc. is the same as used in C for printf() or sprintf(). So if you use "%s%02d", you zero pad the numbers 1 to 9 and get strings like 'user01' and so on.

Thanks a lot. That helps. And that is quite close what I expected.

This question has already been answered. Start a new discussion instead.