-1
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.

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. Commented Feb 8 at 11:07

3 Answers 3

1

Short answer: size - 1 is used as the end point of the loop, but since range() excludes the end value, it might accidentally skip the last character.

It might seem like you need size - 1 because Python string indexing starts at 0. So if the word has 8 characters, the valid indexes are 0 to 7

But in Python, the range() function already stops before the end value. So if you use range(0, size - 1, 2), you're actually stopping at index 6 (because size - 1 is 7, and range() excludes the end).

That’s why you don’t need to subtract 1 — using range(0, size, 2) is correct. Otherwise, the last character might be skipped.

For example, with input "hello":

  • range(0, size - 1, 2) gives indexes 0 and 2 → prints h and l

  • range(0, size, 2) gives indexes 0, 2, and 4 → prints h, l, and o

----------

Also, instead of a loop, you can use slicing:

print("Printing only even index chars:")
print(word[::2])

Example:

Enter a word: hello
Printing only even index chars: hlo 

If you want to separate the letters with commas:

print(", ".join(word[::2]))

This would output:

h, l, o
Sign up to request clarification or add additional context in comments.

Comments

-2

In 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.

Comments

-2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.