福建头条网 / 头条知识 / 正文

大小写转换

2024-04-01 21:19 阅读了

关于大小写转换的知识点,福建头条网将为你整理了下面这些知识。

大小写转换

大小写转换是指将字符串中的大写字母转换为小写字母,或将小写字母转换为大写字母。在编程中,可以使用内置函数或自定义函数来实现大小写转换。

Python中的内置函数:

lower():将字符串中的所有大写字母转换为小写字母。

upper():将字符串中的所有小写字母转换为大写字母。

示例代码:复制# 将字符串中的大写字母转换为小写字母 str1 = "Hello World" str2 = str1.lower() print(str2) # 输出:hello world # 将字符串中的小写字母转换为大写字母 str3 = "hello world" str4 = str3.upper() print(str4) # 输出:HELLO WORLD

自定义函数: 复制def to_lower_case(s): """ 将字符串中的大写字母转换为小写字母 """ res = "" for c in s: if 'A' <= c <= 'Z': res += chr(ord(c) + 32) else: res += c return res def to_upper_case(s): """ 将字符串中的小写字母转换为大写字母 """ res = "" for c in s: if 'a' <= c <= 'z': res += chr(ord(c) - 32) else: res += c return res # 测试 str1 = "Hello World" str2 = to_lower_case(str1) print(str2) # 输出:hello world str3 = "hello world" str4 = to_upper_case(str3) print(str4) # 输出:HELLO WORLD

以上代码中,to_lower_case()函数将字符串中的大写字母转换为小写字母,to_upper_case()函数将字符串中的小写字母转换为大写字母。在函数中,使用了ASCII码进行大小写转换。

大小写转换

相关推荐:
猜你喜欢: