Reputation: 49
s = 'Abrakadabra'
for k in (len(s)):
if (k%2==1):
print(s[k])
This code doesn't work, what is the problem?
Upvotes: 0
Views: 4545
Reputation: 130
You are trying to iterate through int (len(s))
i think you're just simply missing the range
function
s = 'Abrakadabra'
for k in range(len(s)):
if k%2==1:
print(s[k])
also much simlpler version is could be done with:
>>> s[1::2]
'baaar'
let's break it down:
s[1: :2]
^ ^ ^ ^
|-|-|-|--- string to use
|-|-|--- index to start from (1 for even, zero or ' ' for odd)
|-|--- index to stop at - space means "till the end"
|----step to take - 2 for every second, 3 for every third and so on
Upvotes: 4
Reputation: 539
You want to iterate over the range
of len(s)
s = 'Abrakadabra'
for k in range(len(s)):
if (k%2==1):
print(s[k])
and even easier pythonic way is
print(s[1::2])
Upvotes: 1
Reputation: 46901
you are missing the range
to iterate over: for k in range(len(s)):
...
you could also use enumerate
:
s = 'Abrakadabra'
for i, x in enumerate(s):
if i % 2 == 1:
print(x)
Upvotes: 0