Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的title()方法在类似单词的情况下编写函数';T_Python_Methods_Title - Fatal编程技术网

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)
演示