Q4

1. 題目

2. 代碼

3. 總結(jié)


題目

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)
2.Other Solution
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])
總結(jié)
>>> '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'``` 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容