Reputation: 151
I want to use the *args to input the name and change the even numbers for the character to Upper Case and odd number character to lower case. For example, Myname
-> MyNaMe
I used the following code for the operation. But it is output all the characters as upper case. (If I add any random variable under myfunc1(x), then it is working properly.)
Using *args :
def myfunc1(*args):
result=''
for i in range(0,len(args)):
if i%2==0:
result+=args[i].upper()
else:
result+=args[i].lower()
print(result)
myfunc1('My Name') # prints "MY NAME"
Using random Variable:
def myfunc1(my_string):
result=''
for i in range(0,len(my_string)):
if i%2==0:
result+=my_string[i].upper()
else:
result+=my_string[i].lower()
print(result)
myfunc1('Myname') # prints MyNaMe
Upvotes: 1
Views: 4545
Reputation: 4284
You can iterate over your string like this:
Code:
def myfunc1(my_string):
print(''.join([char.upper() if idx % 2 == 0 else char.lower() for idx, char in enumerate(my_string)]))
myfunc1("My Name")
Output:
> My nAmE
Upvotes: 1
Reputation: 1561
Your are passing the args
variable with *
. That means you are passing a list of arguments. So, when you write myfunc1('My Name')
, the function is getting as argument the string 'My Name'
and an empty argument. So, when you iterate args, the first for will work over 'My name' and the second for will work over the empty argument. The solution is simple, remove the *
from the declaration of your function.
Upvotes: 1
Reputation: 1444
args
is a list of arguments. Since you're sending 1 argument, args=('My Name',)
.
Correct code
def myfunc1(*args):
result=''
for i in range(0,len(args[0])):
if i%2==0:
result+=args[0][i].upper()
else:
result+=args[0][i].lower()
print(result)
myfunc1('My Name')
Upvotes: 2