python - 将现有大写字母保留在字符串中

标签 python string python-3.x

我正在使用以下代码将每个单词的首字母更改为大写,除了一些琐碎的单词(a、of 等)

f = open('/Users/student/Desktop/Harry.txt').readlines()[2]
new_string = f.title()
print (new_string)

我还想做的是让那些没有如上所述大写的异常(exception)词,但也有任何已经有大写字母的词(例如 CHINA,NSW),这些字母将被保留。

最佳答案

像这样:

使用str.capitalize:

为什么?

>>> "CAN'T".title()
"Can'T"

>>> "CAN'T".capitalize()
"Can't"

代码:

>>> strs = """What i would also like to do is have those exception words not capitalised as 
stated above but also have that any word that already has capitals letters
( For e.g. CHINA, NSW etc. ) that those letters will be retained."""
>>> words = {'a','of','etc.','e.g.'}  #set of words that shouldn't be changed
>>> lis = []
for word in strs.split():
    if word not in words and not word.isupper(): 
        lis.append(word.capitalize())
    else:    
        lis.append(word)
...         
>>> print " ".join(lis)
What I Would Also Like To Do Is Have Those Exception Words Not Capitalised As Stated Above But Also Have That Any Word That Already Has Capitals Letters ( For e.g. CHINA, NSW etc. ) That Those Letters Will Be Retained.

关于python - 将现有大写字母保留在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511275/

相关文章:

python - 类型错误 : __init__() takes at most 2 arguments (4 given)

python - python 中的 maprdb find_by_condition 抛出异常 - 找不到类 com.mapr.db.Condition$Op

python - 在 pandas 中读取文本文件,分隔符作为换行符 (\n),行终止符作为两个换行符 (\n\n)

python - 打印一系列列对齐的列表

两个 URL 编码字符串之间的 Java 区别

java - 在另一个字符串中替换最后一次出现的字符串

python all() 迭代字符串

python - 获取所有可能的类属性的完整列表

Python3 - 如何在 pygame 混音器中更改声音的音量

python - 从字符串末尾开始的字符索引