Strange behavior of .capitalize function

Viewed 44

I've matched strange behavior of .capitalize function with reduce.

from functools import reduce
def camel_case(string):
    return reduce(lambda x,y:x.capitalize()+y.capitalize(),string.split())

and the result of camel_case('camel case word') is 'CamelcaseWord' while when I use .upper(),for example,everything works fine.

What I misunderstand? Thanks everyone for response!

1 Answers

since you use the reduce function, when you call camel_case with 'camel case word' it is equivalent to the following code:

x,y,z = s.split()
(x.capitalize() + y.capitalize()).capitalize() + z.capitalize()

Now, the 3rd capitalize (from left) will turn all characters to lower case and the first character will become upper case so you get

(x.capitalize() + y.capitalize()).capitalize() 

equals to 'Camelcase' and,

z.capitalize()

equals to 'Word'. Hence the result.

Now, when you use upper, calling (x.upper() + y.upper()).upper() is equivalent to x.upper() + y.upper() so you won't notice the difference.

Related