简体   繁体   中英

Python - can't understand this reverse program

This is the code, the main goal of this program is to print the message backwards

message = 'Here is an example'
translated = ''
i = len(message) - 1
while i >= 0:
    translated = translated + message[i]
    i = i - 1
print(translated)

What I can't understand is the 3rd line, the message contains 18 characters but 'i' subtracts one so it's 17, when you run this program every symbol is there, the 5th line prints out the message with i (still 1 character less) and nothing is missing, can anyone explain why is everything there?I know that you can do it with only 2 lines like this

message = 'Here is an example'
print(message[::-1])

but I want to understand the longer program.

大多数语言中的索引以0开头,因此最后一个字符索引将为长度-1

This is an instance of the 1-based to 0-based conundrum.

Lists in python (and most languages) are 0-based. We think in a 1-based fashion. In other words, we start counting from 1. But computers start counting from 0!

So, if we want to iterate through a list, we need to first subtract one from the length. A list that is of length 3 will have 3 elements in it, and their indexes will be 0 through 2. If we try and access something at index 3, we will get an index out of bounds exception.

Does that help?

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