python-3.x - Python 字符串中的 .title()
问题描述
"CIA is a top secret...".title()
产量:
Cia Is A Top Secret...
是否有任何隐藏的功能可以保持大写字母大写,所以我会得到:
CIA Is A Top Secret...
反而?还是我必须自己写?
解决方案
您可以按照以下方式编写自己的内容:
def title_but_keep_all_caps(text, slow = False):
"""Replaces words with title() version - excempt if they are all-caps.
The 'slow = False' way replaces consecutive whitespaces with one space,
the 'slow = True' respects original whitespaces but creates throwaway strings."""
if slow:
t = ' '.join( (org.title() if any(c.islower() for c in org)
else org for org in text.split()) )
else:
t = text
p = {org:org.title() if any(c.islower() for c in org)
else org for org in text.split()}
for old,new in p.items():
t = t.replace(old,new) # keeps original whitespaces but is slower
return t
example ="CIA is a top secret agency..."
print(title_but_keep_all_caps(example))
print(title_but_keep_all_caps(example,True))
输出:
CIA Is A Top Secret Agency...
CIA Is A Top Secret Agency...
推荐阅读
- excel - 此命令要求 RefreshTable 方法上至少有两行源
- php - Wordpress 用 PHP 调用路径
- business-objects - SAP BO - 每月第一天和最后一天之间经过的时间(停机时间)
- ansible - 使 ansible 库存文件安全或在部署之前对其进行验证
- cmake - 使用 CMake,如何识别目标的依赖项
- python - 在 python 的蛇游戏中蛇不吃食物
- .net-core - dotnet 核心中的 [ScriptIgnore] 在哪里?
- python - 基于具有条件的其他列值创建新列
- python - 单视图计量:如何测量单帧视频的高度?
- python - Python追加不适用于二维数组中的axis = 1