Linux 拨号vps windows公众号手机端

python字母大小写转换的方法是什么

lewis 7年前 (2018-04-09) 阅读数 10 #程序编程
文章标签 python

Python中可以使用内置的字符串方法来实现字母大小写转换。以下是几种常用的方法:

  1. 使用upper()方法将字符串中所有字母转换为大写字母:
string = "hello"
new_string = string.upper()
print(new_string)  # 输出 "HELLO"
  1. 使用lower()方法将字符串中所有字母转换为小写字母:
string = "WORLD"
new_string = string.lower()
print(new_string)  # 输出 "world"
  1. 使用capitalize()方法将字符串的首字母转换为大写字母,其余字母转换为小写字母:
string = "hello world"
new_string = string.capitalize()
print(new_string)  # 输出 "Hello world"
  1. 使用swapcase()方法将字符串中的大写字母转换为小写字母,小写字母转换为大写字母:
string = "Hello World"
new_string = string.swapcase()
print(new_string)  # 输出 "hELLO wORLD"

以上方法都会返回一个新的字符串,原始字符串不会被修改。如果需要在原字符串上进行修改,可以将新字符串赋值给原字符串变量。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门