当前位置: 首页 > 图灵资讯 > 行业资讯> Python字符串大小写转换的函数及用法

Python字符串大小写转换的函数及用法

发布时间:2025-11-02 16:21:41

由内部构建的str类代表Python字符串,然后str 类包含哪些方法?Python 它甚至不需要用户查询文档,非常方便,Python 是“自带文档”。

读者需要简单地掌握两个帮助函数:

dir():列出指定类或模块中包含的所有内容(包括函数、方法、类、变量等)。

help():查看函数或方法的帮助文档。

例如,检查一下 str 可在交互式解释器中输入以下命令:

>>>dir(str)
['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__',
'__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__init_subclass__',
'__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__',
'__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__',
'__subclasshook__','capitalize','casefold','center','count','encode','endswith','expandtabs','find',
'format','format_map','index','isalnum','isalpha','isdecimal','isdigit','isidentifier','islower',
'isnumeric','isprintable','isspace','istitle','isupper','join','ljust','lower','lstrip',
'maketrans','partition','replace','rfind','rindex','rjust','rpartition','rsplit','rstrip',
'split','splitlines','startswith','strip','swapcase','title','translate','upper','zfill']

上面列出了 str 类提供的所有方法,包括以“_”开头和“_”结尾的方法,都约定为私有方法,不想直接被外界调用。如果您想查看某种方法的用法,可以使用它 help() 函数。例如,在交互式解释器中输入以下命令:

>>>help(str.title)
Helponmethod_descriptor:

title(...)
S.title()->str

ReturnatitlecasedversionofS,i.e.wordsstartwithtitlecase
characters,allremainingcasedcharactershavelowercase.

从以上介绍可以看出,str 类的 title() 该方法的作用是大写每个单词的首字母,并保持其他字母不变。

在 str 与大小写相关的常用方法如下:

title():将每个单词的首字母改为大写。

lower():将整个字符串改为小写。

upper():将整个字符串改为大写。

例如,如果你想看到它 lower() 该方法的相关用法可以操作以下命令:

>>>help(str.lower)
Helponmethod_descriptor:

lower(...)
S.lower()->str

ReturnacopyofthestringSconvertedtolowercase.

以下代码示范 str 与大小写相关的常用方法:

a='ourdomainiscrazyit.org'
#每个单词的首字母大写
print(a.title())
#字符串中的所有字符都是小写的
print(a.lower())
#字符串中的所有字符都是大写的
print(a.upper())

在操作上述程序时,可以看到以下输出结果:

OurDomainIsCrazyit.Org
ourdomainiscrazyit.org
OURDOMAINISCRAZYIT.ORG

相关文章

Python字符串大小写转换的函数及用法

Python字符串大小写转换的函数及用法

2025-11-02
Python for循环及用法详解

Python for循环及用法详解

2025-11-02
Python中进程与线程的区别是什么

Python中进程与线程的区别是什么

2025-11-02
Python如何进行线程切换

Python如何进行线程切换

2025-11-02
Python函数关键字参数及用法

Python函数关键字参数及用法

2025-11-02
Python函数的高级用法

Python函数的高级用法

2025-11-02