Reputation: 31
I'm new to python and this should be a simple function practice exercise.
I wrote this function that should put in upper case every character of a string in which the index is even, but it didn`t work.
When I wrote a very similar (but not as function), it worked. Why?
h = 'abcdefg'
f = ''
for stuff in h:
if h.index(stuff) % 2 == 0:
f = f + stuff.upper()
else:
f = f + stuff.lower()
print(f)
Output: AbCdEfG
h = 'abcdefg'
def func_test(*a):
f = ''
for stuff in a:
if a.index(stuff) % 2 == 0:
f = f + stuff.upper()
else:
f = f + stuff.lower()
return f
func_test(h)
Output: 'ABCDEFG'
Upvotes: 2
Views: 41
Reputation: 5889
I think it might be a mistake but, at the moment you are passing in args
.
def func(*args)
notice the asterisk before the argument. Doing this in your program will give us
('abcdefg',)
So, take this away and you can easily iterate through the string.
h = 'abcdefg'
def func_test(a):
f = ''
for stuff in a:
if a.index(stuff) % 2 == 0:
f = f + stuff.upper()
else:
f = f + stuff.lower()
return f
print(func_test(h))
tradition create online
x = lambda a: ''.join([let.upper() if count % 2 == 0 else let for count,let in enumerate(a)])
print(x('abcdefg'))
output
AbCdEfG
Upvotes: 5