103k views
0 votes
1. Assume that word is a variable of type String that has been assigned a value . Assume furthermore that this value always contains the letters "dr" followed by at least two other letters. For example: "undramatic", "dreck", "android", "no-drip".

Assume that there is another variable declared , drWord, also of type String . Write the statements needed so that the 4-character substring word of the value of word starting with "dr" is assigned to drWord. So, if the value of word were "George slew the dragon" your code would assign the value "drag" to drWord.

2. Assume that sentence is a variable of type String that has been assigned a value . Assume furthermore that this value is a String consisting of words separated by single space characters with a period at the end. For example: "This is a possible value of sentence."

Assume that there is another variable declared , firstWord, also of type String . Write the statements needed so that the first word of the value of sentence is assigned to firstWord. So, if the value of sentence were "Broccoli is delicious." your code would assign the value "Broccoli" to firstWord.

User Ashcatch
by
4.0k points

1 Answer

3 votes

Answer:

1.word = "George slew the dragon"

startIndex = word.find('dr')

endIndex = startIndex + 4

drWord = word[startIndex:endIndex]

2. sentence = "Broccoli is delicious."

sentence_list = sentence.split(" ")

firstWord = sentence_list[0]

Step-by-step explanation:

The above snippet is written in Python 3.

1. word is initialized to a sentence.

Then we find the the occurence of 'dr' in the sentence which is assign to startIndex

We then add 4 to the startIndex and assign it to endIndex. 4 is added because we need a length of 4

We then use string slicing method to create a substring from the startIndex to endIndex which is assigned to drWord.

2. A string is assigned to sentence. Then we split the sentence using sentence.split(" "). We split based on the spacing. The inbuilt function of split returns a list. The first element in the list is assigned to firstWord. List uses zero based index counting. So. firstWord = sentence_list[0] is use to get first element.

User NSGaga
by
4.5k points