CodeWars---Python第四题

1. 题目
2. 代码
3. 总结

题目

Description:

A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.

Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string – it should behave in the same way even if the case of the minor word string is changed.

Arguments (Haskell)

  • First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string.

  • Second argument: the original string to be converted.

Arguments (Other languages)

  • First argument (required): the original string to be converted.

  • Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass undefined when this argument is unused.

Example:

title_case(‘a clash of KINGS’, ‘a an the of’) # should return: ‘A Clash of Kings’
title_case(‘THE WIND IN THE WILLOWS’, ‘The In’) # should return: ‘The Wind in the Willows’
title_case(‘the quick brown fox’) # should return: ‘The Quick Brown Fox’

代码

  1. my solution
def title_case(title, minor_words=""):
    ans = title.title()
    minor = minor_words.title()
    ans_list = ans.split(" ")
    minor_list = minor.split(" ")
    if minor_words == "":
        return ans
    else:
        for word in minor_list:
            for index, ans_word in enumerate(ans_list):
                if index>0 and word==ans_word:
                    ans_list[index] = word.lower()
        return " ".join(ans_list)
  1. other solutions
def title_case1(title, minor_words=''):
    title = title.capitalize().split()
    minor_words = minor_words.lower().split()
    return ' '.join([word if word in minor_words else word.capitalize() for word in title])

总结

>>> 'i am from a beautiful place'.title()
    'I Am From A Beautiful Place'

>>> 'i am from a beautiful place'.capitalize()
    'I am from a beautiful place'

>>> 'GO Back To HOMe'.lower()
    'go back to home'

整体迁到简书了,^_^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值