字符串转换为大写,无内置方法 [英] Conversion of string to upper case without inbuilt methods

查看:142
本文介绍了字符串转换为大写,无内置方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在不使用任何内置函数(除了ord()和char())的情况下将字符串从小写转换为大写。

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 different thread here , I came up with this.

def uppercase(str_data):
   ord('str_data')
   str_data = str_data -32
   chr('str_data')
   return str_data
print(uppercase('abcd'))

然而我得到一个错误输出:TypeError:ord()期望一个字符,但是长度为8的字符串找到了。在这里失踪?

However I am getting an error output: TypeError: ord() expected a character, but string of length 8 found.What am I missing here?

推荐答案

您需要为输入字符串的每个字符执行ord()。而不是输入字符串:

You need to execute ord() for each character of your input string. instead of the input string:

def uppercase(str_data):
    return ''.join([chr(ord(char) - 32) for char in str_data if ord(char) >= 65])

print(uppercase('abcdé--#'))
>>> ABCDÉ

不加入:

Without join:

def uppercase(str_data):
    result = ''
    for char in str_data:
        if ord(char) >= 65:
            result += chr(ord(char) - 32)
    return result
print(uppercase('abcdé--#λ'))
>>> ABCDÉΛ

这篇关于字符串转换为大写,无内置方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆