How to change any data type into a string in Python?

PythonServer Side ProgrammingProgramming

<p>Any built-in data type converted into its string representation by str() function</p> <pre class="prettyprint notranslate"> &gt;&gt;&gt; str(10) '10' &gt;&gt;&gt; str(11.11) '11.11' &gt;&gt;&gt; str(3+4j) '(3+4j)' &gt;&gt;&gt; str([1,2,3]) '[1, 2, 3]' &gt;&gt;&gt; str((1,2,3)) '(1, 2, 3)' &gt;&gt;&gt; str({1:11, 2:22, 3:33}) '{1: 11, 2: 22, 3: 33}' </pre> <p>For a user defined class to be converted to string representation, __str__() function needs to be defined in it.</p> <pre class="prettyprint notranslate"> &gt;&gt;&gt; class rectangle: def __init__(self): self.l=10 self.b=10 def __str__(self): return 'length={} breadth={}'.format(self.l, self.b) &gt;&gt;&gt; r1=rect() &gt;&gt;&gt; str(r1) 'length = 10 breadth = 10' </pre>
Updated on 30-Jul-2019 22:30:20