194k views
0 votes
The function below takes a string argument sentence. Complete the function to return the second word of the sentence. You can assume that the words of the sentence are separated by whitespace. If the sentence contains less than two words, return None. If the last character of the word you are returning is a comma, semi-colon, period, exclamation point, or question mark, remove that last character.

User Abendt
by
5.7k points

1 Answer

1 vote

Answer:

Following are the code to this question:

def string_argument(val): #Defining a method string_argument

w= val.split() #Define variable that split value

if len(w) < 2: # Define condition to check value length

return None #return value

if w[1][-1] in ",;.!?": #Define condition to check special character

return w[1][:-1] #return second word

return w[1] # return value

print(string_argument("good morning hello?")) #call method and print return value

print(string_argument("hii morning, DEV"))#call method and print return value

print(string_argument("how are you? MR"))#call method and print return value

print(string_argument("dev lambda. Who"))#call method and print return value

print(string_argument("thanks")) #call method and print return value

Output:

None

morning

None

lambda

None

Step-by-step explanation:

In the given python program, a method "string_argument" is declared, that accepts a value val in its parameter, inside the method, another variable "w" is used, that splits the argument value. In the next line, two if conditional block is used which can be described as follows:

  • In the first block, it will check the length, it is not less then 2, if this condition is true it will return none.
  • In the second if the block it will check, that variable val holds any special character in its second word so, it will return the second word.
User Ahi Tuna
by
6.2k points