leetcode——709. 转换成小写字母(大小写转换,ord和chr)

解法1:
class Solution:
    def toLowerCase(self, str):
       
        str=str.lower()
        return str
解法2:
class Solution:
    def toLowerCase(self, str):
        str=list(str)
        for i in range(len(str)):
            if str[i]>='A'and str[i]<='Z':
                x=ord(str[i])+32
                str[i]=chr(x)
        return ''.join(str)

解法2比解法1的用时要短。
知识回顾
     1、list(str):强制类型转换
     2、lower():将字符串全部转换为小写,
     3、upper():将字符串全部转换为大写
     4、capitalize():将字符串首字母变为大写
     5、title():将每个首字母变为大写
     6、swapcase():大小写互换
2-6的这五个方法都是生成新的字符串,并不会对原字符串做任何修改。
 

s='as fd sfSD SD aSD'
ss=s.lower()
print(s,"+lower+",ss)
ss=s.upper()
print(s,"+upper+",ss)
ss=s.capitalize()
print(s,"+capitalize+",ss)
ss=s.title()
print(s,"+title+",ss)
ss=s.swapcase()
print(s,"+swapcase+",ss)
'''执行结果:
as fd sfSD SD aSD +lower+ as fd sfsd sd asd
as fd sfSD SD aSD +upper+ AS FD SFSD SD ASD
as fd sfSD SD aSD +capitalize+ As fd sfsd sd asd
as fd sfSD SD aSD +title+ As Fd Sfsd Sd Asd
as fd sfSD SD aSD +swapcase+ AS FD SFsd sd Asd
'''
     7、ord():将字符转为ASCII码
     8、chr():将ASCII码转换为字符
print(ord('A'))
print(chr(65))
'''
A-Z:65-90
a-z:97-122
执行结果:
65
A
'''
 

你可能感兴趣的:(leetcode——709. 转换成小写字母(大小写转换,ord和chr))