Answer:
I am writing a Python program:
def string_type(string):
if string=="": //if the string is empty
return "empty"
elif string.count(".")>1: #if the period sign occurs more than once in string
if string.count("\\"): #checks if the new line occurs in the string
return "page" #if both the above cases are true then its a page
return "paragraph" # if the period sign condition is true then its a para
elif string.count(" ")>=1: #if no of spaces in string occur more than once
return "sentence" #returns sentence
elif len(string)==1: # if length of the string is 1 this
return "character" #returns character
else: #if none of the above conditions is true then its a word
return "word" #returns word
Step-by-step explanation:
def string_type(string): this is the definition of method string_type which takes a string as argument and determines whether the type of string is a word, paragraph, page, sentence or empty.
if string=="" this if condition checks if the string is empty. If this condition is true then the method returns "empty"
elif string.count(".")>1 This condition checks if the string type is a paragragh
string.count(".")>1 and if string.count("\\") both statements check if the string type is a page.
Here the count() method is used which is used to return the number of times a specified string or character appears in the given string.
Suppose the string is "Paragraphs need to have multiple sentences. It's true.\\ However, two is enough. Yes, two sentences can make a paragraph."
The if condition first checks if count(".")>1 which means it counts the occurrence of period i.e. "." in the string. If the period occurs more than once this means it could be a page. But it could also be a paragraph so in order to determine the correct string type another if statement if string.count("\\") inside elif statement determines if the string is a page or not. This statement checks the number of times a new line appears in the string. So this distinguishes the string type paragraph from string type page.
elif string.count(" ")>=1: statement determines if the string is a sentence. For example if the string is "i love to eat apples." count() method counts the number of times " " space appears in the string. If the space appears more than once this means this cannot be a single word or a character and it has more than one words. So this means its a sentence.
elif len(string)==1: this else if condition checks the length of the string. If the length of the string is 1 this means the string only has a single character. Suppose string is "!" Then the len (string) = 1 as it only contains exclamation mark character. So the method returns "character" . If none of the above if and elif conditions evaluates to true then this means the string type is a word.