简体   繁体   中英

Why is my string function [str()] working incorrectly?

I'm trying to print the nth term of a string, but beyond a certain term this doesn't work.

I set up my number to be such that the 2nd term is 2, 3rd term is 3 etc. 16th term is 6. This all works correctly up until term 17, where a number 8 is printed which doesn't make any sense. Strangely, this is working correctly for the first 16 terms but the 17th it gets wrong. When I try to print the 18th term, I get an error saying the string index is out of range, which it clearly isn't.

print(str(0.2345678901234567890)[17])

Interestingly, if I go with the notation:

 print("0.2345678901234567890"[17]) 

then it works perfectly well with every element being printed correctly. Hence I believe there is something wrong with the str() function, but I can't find anything online.

You should check the results of appying str() :

>>> str(0.2345678901234567890)
'0.234567890123'

it rounds up the number, and there are not enough digits to get #17.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM