So I am still in the beginning stages of learning Python--and coding as a whole for that matter.
My question is why can I not change items in a Python list using a step, like this:
def myfunc2(string):
new = list(string)
new[0::2] = new[0::2].upper()
new[1::2] = new[1::2].lower()
return '' .join(new)
myfunc2('HelloWorld')
I want to make every other letter upper and lower case, starting at index 0.
I had already seen a solution posted by another user, and although this other solution worked I had trouble understanding the code. So, in my curiosity I tried to work out the logic myself and came up with the above code.
Why is this not working?
new[0::2]
returns a list, which does not have an upper
method . Same goes for new[1::2]
and lower
.
You can achieve your goal with map
:
def myfunc2(string):
new = list(string)
new[0::2] = map(str.upper, new[0::2])
new[1::2] = map(str.lower, new[1::2])
return '' .join(new)
print(myfunc2('HelloWorld'))
# HeLlOwOrLd
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.