Python 程序将每个单词的首字母大写
pythonserver side programmingprogramming更新于 2025/12/19 6:04:17
假设我们有一个包含英文小写字母的句子。我们必须将每个单词的首字母转换为大写。
因此,如果输入为 s = "i love my country",则输出为 "I Love My Country"
要解决这个问题,我们将遵循以下步骤 −
- words := 来自 s 的单词列表
- ret := 一个新的空白列表
- 对于 words 中的每个 i,执行
- 使用 capitalize() 函数将 i 的首字母大写并将其插入到 ret 中
- 连接 ret 中存在的每个单词并用空格分隔并返回
示例
让我们看看下面的实现以便更好地理解
def solve(s):
words = s.split(' ')
ret = []
for i in words:
ret.append(i.capitalize())
return ' '.join(ret)
s = "i love my country"
print(solve(s))
输入
"i love my country"
输出
I Love My Country
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

