[Tutor] Concatenation
Mats Wichmann
mats at wichmann.us
Fri Aug 19 14:20:34 EDT 2022
On 8/19/22 11:59, Joel Goldstick wrote:
> On Fri, Aug 19, 2022 at 1:46 PM Gibson Green via Tutor <tutor at python.org> 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.
>>
>> Gibson.
>>
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>
> There are lots of ways. The most recent addition to python are
> f-strings. This works:
>
>>>> age = 5
>>>> print (f"my age isn't {age}")
> my age isn't 5
yes - in which the "formatted string literal" implicitly does the
conversion of the value of "age" into a string, since it knows that the
objective is to produce a string, something Python did not know was
intended in the original version.
That original version can also be forced:
print('Congratulations, you are now ' + str(age) + ' years old')
but that's kind of suboptimal, because then you have to remember that
something in that line needs to have a type conversion done, and write
it that way. Why not let the language do the work for you when possible?
More information about the Tutor
mailing list