-2

I am able to perform the capitalization function using the below for loop and enumerate function.

wordlist = list(word)
for i,v in enumerate(wordlist):
    if i%2 != 0:
        wordlist[i] = v.upper()
    else:
        wordlist[i] = v.lower()
        word2 = "".join(wordlist)
print(word2)

However when I try to put it into the function in python, I am not able to reproduce the same result as above:

def myfunc(*word):
    wordlist = list(word)
    for i,v in enumerate(wordlist):
        if i%2 != 0:
            wordlist[i] = v.upper()
        else:
            wordlist[i] = v.lower()
            word = "".join(wordlist)
    return (word)

Can anyone help me with my question?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 2
    `word` in in your function is a tuple because you are using *word and so `list(word)` is not returning what you expect from it. Do you need to pass multiple words in the function parameter? – Ankit Jaiswal Sep 21 '18 at 02:44
  • @AnkitJaiswal Yup, it's returning `[word]`, and default it's `(word)`, because thats basically `*args`, from [this question](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – U13-Forward Sep 21 '18 at 02:46
  • Why did you use a `def myfunc(*word):` variable-length argument signature here? – juanpa.arrivillaga Sep 21 '18 at 02:55
  • Also, your `"".join(wordlist)` is indented too much. – kindall Sep 21 '18 at 03:16
  • @kindall Oh yeah, why not just at the end – U13-Forward Sep 22 '18 at 23:54

3 Answers3

2

No need to unpack (*) that makes word equal to (word,) i.e. single element tuple:

def myfunc(word):
    wordlist = list(word)
    for i,v in enumerate(wordlist):
        if i%2 != 0:
            wordlist[i] = v.upper()
        else:
            wordlist[i] = v.lower()
            word = "".join(wordlist)
    return (word)

Or easier:

def myfunc(word):
    word=list(word.lower())
    for i,v in enumerate(word):
        if i%2 != 0:
            word[i] = v.upper()
    return ''.join(word)

Better:

def myfunc(word):
    word=list(word.lower())
    word[1::2]=map(str.upper,word[1::2])
    return ''.join(word)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

Easier and simpler approach

 def func(word):
        result = ""
        for i in range(len(word)):
            if i % 2 == 0:
                result += word[i].upper()
            else:
                result += word[i]
        return result
robo3t
  • 13
  • 4
0
       word = "prasanna"
       def myfunc(word):
          word=list(word.lower())
          for i,v in enumerate(word):
               if i%2 != 0:
                 word[i] = v.upper()
          print  ''.join(word)
       myfunc(word)