Reputation: 53
I am learning python list and string functions. I need to write a specific function. My function returns correctly the Else task. However, I am not able to capitalize only the first and last letter of each word in the given sentence. Thank you for your help, I can only use basic functions as given in the hints.
Here is the task: If the given sentence starts with *, capitalizes the first and last letters of each word in the sentence, and returns the sentence without *. Else, joins all the words in the given sentence, separating them with a comma, and returns the result.
For example if we call capitalize_or_join_words("*i love python"), we'll get "I LovE PythoN" in return. If we call capitalize_or_join_words("i love python"), we'll get "i,love,python" in return. If we call capitalize_or_join_words("i love python "), we'll get "i,love,python" in return.
Hints: The startswith() function checks whether a string starts with a particular character. The capitalize() function capitalizes the first letter of a string.The upper() function converts all lowercase characters in a string to uppercase. The join() function creates a single string from a list of multiple strings
def capitalize_or_join_words(sentence):
if sentence.startswith('*'):
s = sentence.replace('*','')
s2 = s.split()
s3 = []
for word in s2:
s3 += word.capitalize()
temp = ",".join(s3)
sentence_revised = temp
else:
s = sentence.split()
sentence_revised = ",".join(s)
return sentence_revised
Upvotes: 0
Views: 2544
Reputation: 1
def capital(strings):
if strings.startswith("*"):
strings = strings.replace("*", "")
strings = result = strings.title()
result = ""
for word in strings.split():
result += word[:-1] + word[-1].upper() + " "
return result[:-1]
else:
strings = strings.split()
result = ",".join(s)
return result
Upvotes: 0
Reputation: 122
Here is what I came up with:
def capitalize_word(word):
if not word:
return ''
if len(word) < 3:
return word.upper()
return word[0].capitalize() + word[1:-1] + word[-1].capitalize()
def capitalize_or_join_words(sentence):
if sentence.startswith('*'):
words = sentence.replace('*', '').split()
return ' '.join(capitalize_word(word) for word in words)
words = sentence.split()
return ','.join(words)
Upvotes: 1
Reputation: 1496
In [1]: string = "My name is amir saleem"
...: ' '.join([i[0].upper()+i[1:-1] + i[-1].upper() for i in string.split()])
Out[1]: 'MY NamE IS AmiR SaleeM'
Upvotes: 0