[Tutor] Accessing a tuple of a dictionary's value

Mats Wichmann mats at wichmann.us
Fri Aug 24 11:14:11 EDT 2018


On 08/24/2018 03:02 AM, Alan Gauld via Tutor wrote:
> CCing list, please always use Reply-All or Reply-List when responding
> to the tutor list so that everyone gets a chance to reply.
> 
> 
> On 24/08/18 00:35, Roger Lea Scherer wrote:
>>
>> Lots of code missing, but the line I'm interested in is this:
>> print("Your number  " + str(numerator) + "/" + str(denominator) + " 
>> is approximately  " + str(fractions[ranges[i][0]][0]) + "/" +
>> str(fractions[ranges[i][0]][1]))
>> I get this output:
>> Your number  37/112  is approximately  1/3
>>
>> From this line:
>> print("Your number ",  numerator, "/",  denominator, " is
>> approximately ", fractions[ranges[i][0]][0], "/",
>> fractions[ranges[i][0]][1])
>> I get this output:
>> Your number  37 / 112  is approximately  1 / 3
>>
>> I'm being picky. I don't like the spaces between the 37 and 112 and 1
>> and 3...
> 
>> my question is: Is there another way other than these two to
>> print without all the str nonsense and not get the spaces
> 
> Yes, use string formatting. 

In addition, let's understand what is happening above.


print("Your number ",  numerator, "/",  denominator, " is approximately
", fractions[ranges[i][0]][0], "/", fractions[ranges[i][0]][1])

You are doing two things in this line
1. construct a string
2. print the string

The constructed string is never assigned a name, so it is not saved
after the print function is done with it (no more references), but
that's what is happening. In constructing the string, there are about a
zillion options, in this case it is "adding" smaller string pieces together.

Try:

s = "hello" + "world"
print(s)

no spaces :)

the string class provides a "+" operator which is just concatenation.
So when building up a new string this way, put spaces in if you want
them, and don't put spaces in if you don't.   If your intent it to
nicely format a string for visual display on your terminal or to a file,
then string concatenation is a more cumbersome route than tools which
are designed for the purpose, but there are plenty of good uses for it
as well.



More information about the Tutor mailing list