Python 中的 String.capwords() 方法
string.capwords
方法:
- 使用 str.split() 方法将字符串拆分为单词。
- 使用 str.capitalize() 方法将每个单词大写。
- 使用 str.join() 方法将大写单词连接成字符串。
from string import capwords
my_str = 'jiyik www com'
result = capwords(my_str)
print(result) # 👉️ 'Jiyik Www Com'
string.capwords()
方法将每个单词中的第一个字符转换为大写,其余的转换为小写。
from string import capwords
my_str = 'JIYIK WWW COM'
result = capwords(my_str)
print(result) # 👉️ 'Jiyik Www Com'
如果我们需要将列表中每个单词的首字母大写,也可以使用 capwords()
方法。
from string import capwords
my_list = ['bobby hadz', 'dot com']
result = [capwords(item) for item in my_list]
print(result) # 👉️ ['Bobby Hadz', 'Dot Com']
我们使用列表推导来迭代列表并将每个项目传递给 capwords()
方法。
string.capwords()
方法对字符串中的每个单词使用 str.capitalize() 方法。
tr.capitalize
函数返回字符串的副本,其中第一个字符大写,其余字符小写。
print('jiyik'.capitalize()) # 👉️ 'Jiyik'
print('WWW'.capitalize()) # 👉️ 'Www'
请注意,还有一个 str.title()
方法。
str.title
方法返回字符串的标题版本,其中单词以大写字符开头,其余字符为小写。
my_str = 'jiyik www'
result = my_str.title()
print(result) # 👉️ "Jiyik Www"
但是,该算法还将撇号后的字符转换为大写。
my_str = "it's him"
result = my_str.title()
print(result) # 👉️ "It'S Him"
string.capwords
方法没有这个问题,因为它只在空格上分割字符串。
from string import capwords
my_str = "it's him"
result = capwords(my_str)
print(result) # 👉️ "It's Him"
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。