1 Star 0 Fork 324

noobyang/Python

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
title.py 1.28 KB
一键复制 编辑 原始数据 按行查看 历史
Aakash Giri 提交于 2023-10-15 00:17 +08:00 . Add Title Case Conversion (#10439)
def to_title_case(word: str) -> str:
"""
Converts a string to capitalized case, preserving the input as is
>>> to_title_case("Aakash")
'Aakash'
>>> to_title_case("aakash")
'Aakash'
>>> to_title_case("AAKASH")
'Aakash'
>>> to_title_case("aAkAsH")
'Aakash'
"""
"""
Convert the first character to uppercase if it's lowercase
"""
if "a" <= word[0] <= "z":
word = chr(ord(word[0]) - 32) + word[1:]
"""
Convert the remaining characters to lowercase if they are uppercase
"""
for i in range(1, len(word)):
if "A" <= word[i] <= "Z":
word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :]
return word
def sentence_to_title_case(input_str: str) -> str:
"""
Converts a string to title case, preserving the input as is
>>> sentence_to_title_case("Aakash Giri")
'Aakash Giri'
>>> sentence_to_title_case("aakash giri")
'Aakash Giri'
>>> sentence_to_title_case("AAKASH GIRI")
'Aakash Giri'
>>> sentence_to_title_case("aAkAsH gIrI")
'Aakash Giri'
"""
return " ".join(to_title_case(word) for word in input_str.split())
if __name__ == "__main__":
from doctest import testmod
testmod()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/noobyang/Python.git
git@gitee.com:noobyang/Python.git
noobyang
Python
Python
master

搜索帮助