views:

112

answers:

4

Hi I am quite new to python and this is probably quite a basic question but the help would be much appreciated.

I would like to put an int within a string. This is what I am doing at the moment..

end = smooth(data,window_len=40)
plot.plot(time[0:len(end)],end)
plot.savefig('hanning(40).pdf') #problem line

I have to run the program for several different numbers instead of the two 40's. So I'd like to do a loop but inserting the variable like this doesn't work:

plot.savefig('hanning',num,'.pdf')

Thanks!

+6  A: 
plot.savefig('hanning(%d).pdf' % num)

The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:

http://docs.python.org/library/stdtypes.html#string-formatting-operations

Amber
thanks a lot that will be useful in the future
Gish
+1  A: 

Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().

"hello " + str(10) + " world" = "hello 10 world"

Hope that helps!

goggin13
cheers that was what I was looking for
Gish
@Gish: on seeing the other posts, I have to recommend Amber's answer as the more correct 'Pythonic' way to handle inserting numbers into strings. I didn't know about the % operator, but I would go with that way.
goggin13
Cool thanks I'll move over the accepted answer
Gish
+1 for recommending someone else's more Pythonic answer even though yours works fine.
Davy8
A: 

You can try something like:

print(" somestring " + str(somenumber))

Yehonatan
@gish answer is much better.
Adam Nelson
+1  A: 

Oh, the many, many ways...

String concatenation:

plot.savefig('hanning' + str(num) + '.pdf')

Conversion Specifier:

plot.savefig('hanning%s.pdf' % num)

Using local variable names:

plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick

Using format():

plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way

Using string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
Dan McDougall