Sudipta Mohanty
Sudipta Mohanty

Reputation: 1

Trying to print the even indexed characters from a string

Trying to print the even indexed characters from a string:

string = input("Please enter your input")
for i in string:
    if (string.index(i))%2==0:
        print(i)

When I apply to the above code It gives me output as:

Please enter your inputhello
h
l
l
o

Upvotes: 0

Views: 6593

Answers (3)

dawg
dawg

Reputation: 104062

You had the right idea.

You can use enumerate to make your code work:

string = input("Please enter your input")
for i,c in enumerate(string):
    if i%2==0:
        print(c)

If you want the ODD characters:

string = input("Please enter your input")
for i,c in enumerate(string):
    if i%2!=0:
        print(c)

Upvotes: 0

Kunal Tanwar
Kunal Tanwar

Reputation: 1291

Like @dawg did but with just a minor correction.

string = input("Please enter your input : ")

for i, c in enumerate(string):
    if i % 2 != 0:
        print(c)

If we just do it not equal to 0 because in python indexing or python counts from 0 but in reality we count from 1 so if remainder is not equal to 0 it will return odd input which exactly what he wanted.

Upvotes: 0

Hemerson Tacon
Hemerson Tacon

Reputation: 2522

Here's a way to do what you want:

for i in string[::2]:
    print(i)

[::2] slices the string. It starts from the beginning of the string and goes until its end increasing the index by 2 per iteration.

Upvotes: 1

Related Questions