Jun-24-2020, 07:49 PM
Hi,
I have an assignment which I am unable to do. I hope someone can help.
The input is a string sentence. If the first element of the input is a * then the first and last characters of every word is to be uppercased. If the first element of the sentence is not a *, then the space between words is to be substituted with a ,.
I tried to write the script but it is not generating the required results. In fact, for one case it is giving an error. The python script is as below. Pls. see if you can correct it.
Avind Gupta
I have an assignment which I am unable to do. I hope someone can help.
The input is a string sentence. If the first element of the input is a * then the first and last characters of every word is to be uppercased. If the first element of the sentence is not a *, then the space between words is to be substituted with a ,.
I tried to write the script but it is not generating the required results. In fact, for one case it is giving an error. The python script is as below. Pls. see if you can correct it.
def concatenate(strings): """ Concatenates the given list into a single string. For example: If the input is ["a","b","c"], returns "abc" """ temp = ''.join(strings) return(temp) def capitalize_or_join_words(sentence): """ 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 sentence, separates with a comma, and returns the result. For example: If the input is "*i love python", returns "I LovE PythoN". If the input is "i love python", returns "i,love,python". """ sentence = sentence.strip() temp = list(sentence) #converts the string into a list of single element string i = 1 if temp[0] == '*': # checks if first element is a * temp[0] = '' # removes the * while i <= len(temp): if temp[i] == ' ': #checks for a blank space temp[i-1].upper() # converts the single element string bofore the blank space to upper case temp[i+1].upper() # converts the single element string after the blank space to upper case i = i+1 temp[len(temp) - 1].upper() #converts the last element in the list to uppercase temp = concatenate(temp) #converts list of strings back into a string using the function as above else: temp = concatenate(temp) #converts list of strings back into a string using the function as above temp.replace(' ', ',') # replaces blank space by , return(temp) def main(): # test capitalize_or_join_words my_string = 'i love python' print(capitalize_or_join_words(my_string)) my_string_2 = '*i love python' print(capitalize_or_join_words(my_string_2)) if __name__ == '__main__': main()Thanks and Regards,
Avind Gupta