Conversion of string to upper case without inbuilt methods

前端 未结 7 1685
轻奢々
轻奢々 2021-01-29 08:28

I am trying to perform conversion from a lowercase to uppercase on a string without using any inbuilt functions (other than ord() and char()). Following the logic presented on a

7条回答
  •  情歌与酒
    2021-01-29 08:41

    The best way, in my opinion is using a helper string, representing the alphabet, if you do not want to use chr() and ord():

    def toUppercase(s):
        alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        result = ''
        for x in s:
            if x not in alphabet or alphabet.index(x)>=26:
                result += x
            else:
                result += alphabet[alphabet.index(x)+26]
        return result
    

    This also handles punctuation such as ; or ..


    Update:

    As per the OP's request, this is a version without index():

    def toUppercase(s):
        alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        result = ''
        for x in s:
            for pos in range(52):
                if alphabet[pos] == x:
                    i = pos
            if x not in alphabet or i>=26:
                result += x
            else:
                result += alphabet[i+26]
        return result
    
    print(toUppercase('abcdj;shjgh'))
    

提交回复
热议问题