【问题标题】:Keeping existing capital letters in string将现有的大写字母保留在字符串中
【发布时间】:2013-07-07 10:22:36
【问题描述】:

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

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

我还想做的是让那些例外词不如上所述大写,但也有任何已经有大写字母的词(例如中国,新南威尔士州),这些字母将被保留。

【问题讨论】:

  • 即使您的问题很清楚,但您显示的代码也无济于事。第一行根本与问题无关。最好是一个示例字符串,所需的new_string 和当前的new_string
  • 所以你想检查你的字符串是否已经全部大写...?
  • 'aBCDe'这样的词呢?

标签: python string python-3.x


【解决方案1】:

类似这样的:

使用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.

【讨论】:

    【解决方案2】:

    对于第一个要求,您可以创建一个包含例外词的列表:

    e_list = ['a', 'of', 'the'] # for example
    

    然后你可以运行这样的东西,使用isupper() 来检查字符串是否已经全部大写:

    new = lambda x: ' '.join([a.title() if (not a in e_list and not a.isupper()) else a for a in x.split()])
    

    测试:

    f = 'Testing if one of this will work EVERYWHERE, also in CHINA, in the run.'
    
    print new(f)
    #Testing If One of This Will Work EVERYWHERE, Also In CHINA, In the Run.
    

    【讨论】:

    • 这将删除不需要大写的单词,而不是保持原样。
    • @interjay 感谢您的反馈,列表理解中缺少 else 语句...
    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2021-01-06
    • 2019-06-08
    • 1970-01-01
    • 2021-08-18
    相关资源
    最近更新 更多