Functions in python you should know about - String.capwords()
String.capwords()
This Function Split the argument into words using
str.split()
, capitalize each word using str.capitalize()
, and join the capitalized words using str.join()
. If the optional second argument sep is absent or None
, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example,
alison heck
should be capitalised correctly as Alison Heck
.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, .
Constraints
- The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.
Output Format
Print the capitalized string, .
Sample Input
chris alan
Sample Output
Chris Alan
Common Solution For This Would Be:-
def solve(s): p=list(s) for i in range(len(p)): if(i==0 and p[i].isalpha()): p[i]=p[i].capitalize() if(p[i].isspace() and p[i+1].isalpha()): p[i+1]=p[i+1].capitalize() i+=1 k="".join(p) return(k)
Unique Solution using the function:-
import string def solve(s): cad=string.capwords(s, sep=" ") return cad
Hope you like the unique solution
This even reduces the complexity of the code and hence a more optimisable solution
For getting daily such updates do follow this page.
More on...Python string split()
ReplyDelete