[Tutor] Concatenation

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 19 17:12:13 EDT 2022


On 19/08/2022 13:42, Gibson Green via Tutor wrote:
> How can I concatenation a string statement with an integer? For example: Congratulations, you are now 24 years old. Age variables was declared and converted to an integer. 
> I have:
>   print ( ‘ Congratulations, you are now’ + age+ ‘ years old’)
> 
> Had an error about concatenation between integer and strings . Please  help. Thanks.

The error is because you are trying to use the plus operation on a
string and an integere which is incompatible. You need to conveert the
integer to a string using str()

But print already converts arguments to strings for you so you
don't need the + sign just use:

print( ‘ Congratulations, you are now ’, age, ‘ years old’)

Or, more generally use a format string as others have suggested.
The format string will work anywhere you need to insert a value
into a string. print() only works for display purposes.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos






More information about the Tutor mailing list