B. Allan
B. Allan

Reputation: 53

Indexing string in Python

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)

Upvotes: 2

Views: 448

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46869

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)

Upvotes: 3

Bhargav Rao
Bhargav Rao

Reputation: 52101

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

Upvotes: 4

Related Questions