This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by Dan G.
over 10 years

My humble explanation about using the str() function

For a while, I was wondering why my code was working just fine when I wasn’t using the str() function (mentioned in the instructions) on the dictionary keys and values. Here is my original code:

d = {'x': 9, 'y': 10, 'z': 20}
      
for key in d:
    # Your code here!
    print key,d[key]

It outputs:

y 10
x 9
z 20
None

As you can see, it works just fine. As does this code: d = {‘x’: 9, ‘y’: 10, ‘z’: 20}

for key in d:
    # Your code here!
    print str(key)+' '+str(d[key])

This outputs:

y 10
x 9
z 20
None

As you can see, they are basically the same code. My assumption is that using the comma, as in the first code, between values automatically converts everything to a string as well as inserts a space in between. This type of code should be fine unless you don’t want a space in between strings. For that you will have to concatenate with a + symbol and use the str() functions on the keys and values of a dictionary.

I hope this helps some of you out there understand a little better.

Answer 5252d288abf821788c0001f3

1 vote

Permalink

Thanks Dan, this helped me a lot :)

points
Submitted by PygmyDust
over 10 years

Answer 5204906a548c35eb4f0005da

-4 votes

Permalink

to concatenate stuff, stuff needs to be strings, or you might end up doing addition instead..! and int+string doesn’t make too much sense

points
Submitted by Jonatan
over 10 years

2 comments

Wow, do you know what you are talking about?

r mora over 10 years

I guarantee he does. Read the last paragraph of the lesson again.