Search code examples
pythonfunctioncapitalize

Python function that capitalizes entire word


So I have created a python function:

def capitalize(x):
  for a in x:
    a.capitalize()
  print x

capitalize("heey")

It is supposed to turn the argument "heey" into "HEEY". But it does not work. It prints "heey". What's up?


Solution

  • capitalize() is not an in-place operation. It doesn't modify the original string but instead it returns the capitalized version. You need to save this value in a variable. For example, the following code:

    a = "heey"
    a.capitalize()
    b = a.capitalize()
    print("a = " + a)
    print("b = " + b)
    

    has output:

    a = heey
    b = Heey
    

    also, if you're going to make all chars uppercase, just call upper() instead, but if you absolutely want to use capitalize() you can do this:

    def capitalize(x):
        y = ""
        for a in x:
            y += a.capitalize()
        print(y)
    
    capitalize("heey")
    

    output:

    HEEY
    

    and here's a shorter version that does the same thing:

    def capitalize(x):
        y = "".join([a.capitalize() for a in x])
        print(y)