whats the use of str(i) ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

whats the use of str(i) ?

plz help

25th Feb 2017, 5:07 AM
Kurian John
Kurian John - avatar
6 Answers
+ 9
To convert variable i to string type.
25th Feb 2017, 5:10 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
@Kurian John: You can print values of any type. What you cannot do, is concatenate string with another type than string... You can write: print(42) ... but not: print('number: '+42) You must do: print('number: '+str(42))
25th Feb 2017, 7:01 AM
visph
visph - avatar
+ 1
str method calls i object's magic method __str__(self), which returns string representation of object. For example we've got class Dog class Dog: __init__(self): ...... __str__(self): return "I am a dog!" i = Dog() str(i) #will return "I am a dog!"
25th Feb 2017, 9:23 AM
Kilrog
Kilrog - avatar
0
can only the values printed after converting it to string
25th Feb 2017, 5:17 AM
Kurian John
Kurian John - avatar
0
Magical just accents that those methods are special. They used to describe how your non standard object will reply to some built in python methods like comparison, multiplication or converting to basic types. For example __eq__ shows if two instances are equal. Let's say we got class Dog with property weight. And __eq__ will return True if weights of two instances of Dog are equal. So the condition dog1 == dog2 will trigger method __eq__ written by you inside Dog class. The same works for >=, >, int(), str(), float(), *, **, // and so on.
25th Feb 2017, 6:21 PM
Kilrog
Kilrog - avatar
- 1
how to easly understand magical methord in phython ?
25th Feb 2017, 3:24 PM
Kurian John
Kurian John - avatar