Skip to Main Content
Blog

Change String Case to Title Case in Python

Change String Case to Title Case in Python

def main():
	"""
	Converts a string to title case.
	"""

	text = input("Enter string: ")
	result = to_title_case(text)
	print(result)


def to_title_case(text: str) -> str:
	if not text:
		return text

	chars = list(text)
	for i in range(1, len(chars)):
		if chars[i - 1].isspace() and chars[i].isalpha():
			chars[i] = chars[i].upper()

	if chars[0].isalpha():
		chars[0] = chars[0].upper()

	return "".join(chars)


if __name__ == "__main__":
	main()