A string is composed of characters each of which has a numeric index starting from 0. Thus, the string “python” has 6 characters with ‘p’ at index 0, ‘y’ at index 1 and so on.
Index of last character will always be equal to the length of string – 1.
Characters at even position will be those whose index is divisible by 2.
This post will demonstrate different ways of printing all the characters at even position in a string.

Method 1: Using string slicing
Python’s extended slicing operator enables extracting characters at specified intervals in a string. Example is given below.

# read a string
str = input("Enter a string\n")
# create a string with characters at multiples of 2
modified_string = str[::2]

Above program reads a string as input and creates a new string with characters at index which are multiples of 2. Expression str[::2] fetches all characters in a string which have an index difference equal to the value supplied at the right starting from the value at the left.
Value at left hand of operator :: is assumed to be 0 if not supplied. Thus, the expression str[::2] can also be written as str[0::2].
Output of the program will be

Enter a string
codippa the website

For printing odd characters, we need to start with characters starting at position 1 with a difference of 2. Slicing operator in this case will be written as str[1::2].

Method 2: Using while loop
Iterate over the characters of the string using a while loop and increment the index by 2 in each iteration as shown in the code below

index = 0
# iterate over string
while index < len(str):
    # print character at index
    print(str[index], end='')
    # increment index by 2
    index = index + 2

index is initialized to 0. A while loop iterates over the string starting from 0 till the length of string which is calculated using len function.
end attribute is required for printing characters at the same line otherwise the characters will be printed on separate lines.

Enter a string
codippa the website

Method 3: Using for loop
This method is similar to the above method in that it uses a loop to iterate over the string but the loop is a for loop.
In every iteration, it checks the current index to be even by calculating the remainder of division of index by 2.
If the remainder is 0, then the index is even and it prints the character at current index.

# iterate over string
for index in range(len(str)):
    # check if index is divisible by 2
    if index % 2 == 0:
        # print character at index
        print(str[index], end='')

Same logic can be used in the previous approach that uses while loop as well.
If you are familiar with any other approaches, do comment in the space below.


Leave a Reply