0

What does ( str ) actually do in Python?

13th Jun 2019, 7:43 AM
Om Mule
Om Mule - avatar
5 Answers
+ 1
In 5+5, '+' is used to add two numbers. The result is 10. In '5'+'5', '+' is used to concatenate two strings. The result is '55'. In '5'+5, (one string and one number), python doesn't know what to do. Add a number to a string? Concatenate a string and a number? It will raise an exception unless you either convert the number to a string: '5'+str(5) = '5'+'5' = '55' or the string to a number: int('5')+5 = 5+5 = 10.
13th Jun 2019, 8:06 AM
Anna
Anna - avatar
0
Mmh assuming you're talking about the str(argument) function, it actually converts the argument given to the function into it's string representation Otherwise, I've no idea what you're talking about
13th Jun 2019, 8:02 AM
ThewyShift
ThewyShift - avatar
0
Yes I am talking about the function but in simple calculator.program they have given Result= str(num1 +num2) why is that ??
13th Jun 2019, 8:06 AM
Om Mule
Om Mule - avatar
0
Well in python, we can't add directly numbers (int, float) with strings. If we want to do so, we need to convert those numbers into string beforehand, the we can add them to the string we want to print
13th Jun 2019, 8:09 AM
ThewyShift
ThewyShift - avatar
0
It is the string class, if you already were familiar with OOP concepts, you would know, that when you call str, as str() you actually call str.__init__ or str.__new__, which creates a new object, a new string. If you called str as str(6) It would call this: class str: def __init__(self, x): if type(x) == int: statements to convert integer x to string. Actually I really suspect that the builtin constructors have some special attributes.
13th Jun 2019, 8:34 AM
Seb TheS
Seb TheS - avatar