leetcode 709 To Lower Case

Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

Example 1:

Input: "Hello"
Output: "hello"

Example 2:

Input: "here"
Output: "here"

Example 3:

Input: "LOVELY"
Output: "lovely"

题目非常简单,就是将字符串中的大写字母转换为小写字母

C++:

class Solution {
public:
    string toLowerCase(string str) {
        int len=str.length();
        for(int i=0;i<len;i++)
            if(str[i]>='A'&&str[i]<='Z')
            str[i]+=32;
        return str;
    }
};

python3:

class Solution:
    def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        str = str.lower()
        return str

刚开始学python python不太会写,只会调用lower方法。查看了更好的方法。

class Solution:
    def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        s = ""
        for i in str:
            if ord(i) < ord('a') and ord(i) >= ord ('A'):
                s += chr(ord(i) + 32)
            else:
                s += i
        return s

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

猜你喜欢

转载自blog.csdn.net/qq_25406563/article/details/81254049
今日推荐