【问题标题】:title() method in python writing functions when word like aren'tpython中的title()方法在没有类似单词的情况下编写函数
【发布时间】:2019-07-22 14:40:47
【问题描述】:

使用函数

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

【问题讨论】:

    标签: python methods title


    【解决方案1】:

    这应该可行:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多