python中的title()方法在没有类似单词时编写函数

dfuffjeb  于 2022-12-25  发布在  Python
关注(0)|答案(3)|浏览(150)

使用功能

def make_cap(sentence):
    return sentence.title()

试用

make_cap("hello world")
'Hello World'

# it workd but when I have world like "aren't" and 'isn't". how to write function for that

a = "I haven't worked hard"
make_cap(a) 
"This Isn'T A Right Thing"  # it's wrong I am aware of \ for isn\'t but confused how to include it in function
kpbwa7wx

kpbwa7wx1#

这应该行得通:

def make_cap(sentence):
    return " ".join(word[0].title() + (word[1:] if len(word) > 1 else "") for word in sentence.split(" "))

它手动地用空格(而不是任何其他字符)分隔单词,然后将每个标记的第一个字母大写。它通过分隔第一个字母,将其大写,然后连接单词的其余部分来实现这一点。我使用了一个三元if语句,以避免在单词只有一个字母长时使用IndexError

zaqlnxep

zaqlnxep2#

使用字符串库中的.capwords()

import string

def make_cap(sentence):
    return string.capwords(sentence)

演示https://repl.it/repls/BlankMysteriousMenus

5t7ly7z5

5t7ly7z53#

我发现这种方法对于将所有不同类型的文本格式化为标题非常有帮助。

from string import capwords

text = "I can't go to the USA due to budget concerns"
title = ' '.join([capwords(w) if w.islower() else w for w in text.split()])
print(title) # I Can't Go To The USA Due To Budget Concerns

相关问题