word = input("Enter a word: ")
print("Original String is: ", word)
size = len(word)
print("Prnting only even index chars")
for i in range(0, size - 1, 2):
print("index[", i, "]", word[i])
I need to understand whether "size - 1" was a subtraction or something else.
I've tried to replace "size - 1" with just "8" and got the same answer. Because the word has 8 characters.
word = input("Enter a word: ")
print("Original String is: ", word)
size = len(word)
print("Prnting only even index chars")
for i in range(0, size - 1, 2):
print("index[", i, "]", word[i])
I need to understand whether "size - 1" was a subtraction or something else.
I've tried to replace "size - 1" with just "8" and got the same answer. Because the word has 8 characters.
Share Improve this question asked 2 days ago Eugene PashkevichEugene Pashkevich 72 bronze badges New contributor Eugene Pashkevich is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 1- I don't understand why would a person subtract 1 from a valuable "size". I can't see the connection and how it works. – Eugene Pashkevich Commented 2 days ago
2 Answers
Reset to default -1In Python (as in most programming languages), indexes start at 0.
In your case, if the user type "Hello World!", word[0]
will contain the character "H"
, word[1] = "e"
, word[2] = "l"
so on and so forth.
When iterating over each character, the last index accessed will be size - 1
, since size
represents the total number of characters in the string, and indexing starts from 0.
size - 1
is used to ensure that the loop does not include the last character, which is important for both odd and even lengths of the string.
You can replace size - 1
with 8
in the context of an 8-character string, but it is generally better to use size - 1
to make the code more flexible and adaptable to strings of different lengths.