Question

I wrote this bit of code in python to capitalize and print the first 4 characters of any string. But I am getting the output is:

A
P
P
L

The output i need is:

APPL

What changes should i make here then?

def capital(uinput):
    slice4 = uinput[:4]
    for i in slice4:
       j = ord(i)
       j = j - 32
       k = chr(j)
       print k

print capital("apple")
Was it helpful?

Solution

How about using upper()?

>>> s = "apple"
>>> s[:4]
'appl'
>>> s[:4].upper()
'APPL'

Speaking about the code you've written, you can modify it this way to make it work:

def capital(uinput):
    slice4 = uinput[:4]
    result = ""
    for i in slice4:
       j = ord(i)
       j = j - 32
       k = chr(j)
       result += k
    print result

or, the same but in one line without having additional variables:

def capital(uinput):
    print "".join([chr(ord(i) - 32) for i in uinput[:4]])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top