2

I'm trying to print out only the odd indexed characters of an input string. I can't use string slicing but instead must use a loop. How it this done? Here is my code:

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

for each_char in string:
    print("\n%s" % each_char)
0

2 Answers 2

4

You can use the enumerate function

>>> string = input("Please enter a string: ")
Please enter a string: helloworld

>>> for k,v in enumerate(string):
...     if k%2==1:
...         print(v)  # No need \n as print automatically prints newline
... 
e
l
w
r
d
Sign up to request clarification or add additional context in comments.

Comments

3

direct string indexing will also work:

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

for i in range(1, len(string), 2):
    print(string[i])

output:

Please enter a string: hello world
e
l

o
l

note the third (step) argument of range(start, stop[, step]).

and - yes - slicing would be much more elegant.


update: because you asked for it - here the version with slicing (you will find more information about slicing in the python tutorial):

for char in string[1::2]:
    print(char)

2 Comments

Though this is a perfectly valid answer, many pythonistas frown over the use of range. That probably explains the dv. :-)
thanks. i was wondering about that. but if slicing is forbidden the most pythonic code does not answer the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.