python中的title()方法在类似单词的情况下编写函数';T
使用功能python中的title()方法在类似单词的情况下编写函数';T,python,methods,title,Python,Methods,Title,使用功能 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 R
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
这应该起作用:
def make_cap(sentence):
return " ".join(word[0].title() + (word[1:] if len(word) > 1 else "") for word in sentence.split(" "))
它手动将单词按空格(而不是任何其他字符)拆分,然后将每个标记的第一个字母大写。它将第一个字母分开,大写,然后将单词的其余部分连接起来。我使用了三元if
语句来避免单词只有一个字母长时出现索引器。使用字符串库中的.capwords()
import string
def make_cap(sentence):
return string.capwords(sentence)
演示: