力扣709.转换成小写字母

709.转换成小写字母

题目描述:

给你一个字符串 s ,将该字符串中的大写字母转换成相同的小写字母,返回新的字符串。

思考(方法一):

首先大写字母的ASCII码是大写字母A的编号为:65,大写字母Z的编号为90,小写字母a的编号为:97,小写字母z的编号为122;大小写字母之间的编号相差32。

然后遍历字符串中的每个字母,利用ord()函数得到他们的码,判断他们是不是在65到90之间,如果在的话,那就将其ASCII码+32得到相应的小写字母。

最后,字符串的添加有如下方式:

  1. 使用加号 + 运算符:

    pythonCopy codestring1 = "Hello"
    string2 = "World"
    result = string1 + string2
    print(result)  # 输出:HelloWorld
    
  2. 使用字符串的 join() 方法:

    pythonCopy codestrings = ["Hello", "World"]
    result = "".join(strings)
    print(result)  # 输出:HelloWorld
    
  3. 使用 f-string 格式化:

    pythonCopy codestring1 = "Hello"
    string2 = "World"
    result = f"{string1}{string2}"
    print(result)  # 输出:HelloWorld
    

这里我们用的是+号,进行字符串的添加。python代码如下所示:

class Solution:
    def toLowerCase(self, s: str) -> str:
      tmp = ''
      ans = ''
      for i in s:
        if ord(i) >=65 and ord(i)<=90:
          tmp = ord(i)+ 32
          ans= ans + chr(tmp)
        else:
          ans=ans +i
      return ans
思考(方法二):

有一个简单的函数,是str.lower()可以直接换成小写的。

class Solution:
    def toLowerCase(self, s: str) -> str:
      return s.lower()
posted @ 2023-07-06 11:07  软面包  阅读(30)  评论(0)    收藏  举报