Python实现"转换成小写字母"的两种方法

实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串

Example 1:

Input: "Hello"
Output: "hello"

Example 2:

Input: "here"
Output: "here"

Example 3:

Input: "LOVELY"
Output: "lovely"

1:先字符串转列表。然后for循环判断列表中元素并采取对应处理操作。最后列表再转回字符串输出。用到的方法有list(str) + ord() +chr() + "".join()

ord() 函数:是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常

chr():用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符

def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        strList = list(str)
        for i, j in enumerate(strList):
            if j >= 'A' and j <= 'Z':
                strList[i] = chr(ord(j) + ord('a') - ord('A'))
        return "".join(strList)

2:去掉解决方案1中字符串转列表和列表转字符串操作。直接用另一个新字符串代替

def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        newStr = ""
        for j in str:
            if j >= 'A' and j <= 'Z':
                newStr += chr(ord(j) + ord('a') - ord('A'))
            else:
                newStr += j
        return newStr

优雅写法(参考他人)

def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        return "".join(chr(ord(c) + 32) if 65 <= ord(c) <= 90 else c for c in str)

算法题来自:https://leetcode-cn.com/problems/to-lower-case/description/

你可能感兴趣的:(Algorithms)