Title Case

地址:http://www.codewars.com/kata/5202ef17a402dd033c000009/train/python

题目:

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.

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'

代码:

def title_case(title,minor_words=""):
	ans = title.title()
	titleList = ans.split(" ")
	words = minor_words.title()
	wordsList = words.split(" ")
	
	if ans == "":
		return ""
	else:
		for i in range(1,len(titleList)):
			if titleList[i] in wordsList:
				titleList[i] = titleList[i][0].lower() + titleList[i][1:]

	return " ".join(titleList)

  

原文地址:https://www.cnblogs.com/HpuAcmer/p/4031953.html