I not get str()


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>

```python

Replace this line with your code.

<do not remove the three backticks above>

#2

We will need a link to the exercise, please. Thanks.

Python, like any other language, has built-in functions for converting data types so operands can be of the same type.

"1" + 1

The above expression illustrates mixed data types, (string and number, respectively) which are incompatible types. Whomever heard of adding a string character to a number?

>>> "1" + 1
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    "1" + 1
TypeError: Can't convert 'int' object to str implicitly
>>> 

We can do one two things with the expression:

  1. Form a concatenated string; or,
  2. Produce a sum.

In the first case,

>>> "1" + str(1)
'11'
>>> 

and in the second,

>>> int("1") + 1
2
>>> 

Matching data types is especially important when storing and transmitting expressions. Python will have a problem printing mixed data,

>>> print ("There are " + 0b10 + " kinds of people. Those who understand binary, and those who don't.")
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print ("There are " + 0b10 + " kinds of people. Those who understand binary, and those who don't.")
TypeError: Can't convert 'int' object to str implicitly
>>> 

However, using the built-in, str() function,

>>> print ("There are " + str(0b10) + " kinds of people. Those who understand binary, and those who don't.")
There are 2 kinds of people. Those who understand binary, and those who don't.
>>> 

Read up on datatypes in Python and this will help you with both this function, and all the others in the toolbox.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.