简体   繁体   中英

Simple Code in Python to change the Upper Case and Lower Case

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

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')

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM