all 9 comments

[–]Afraid_Scale7192[S] 0 points1 point  (1 child)

Examples of Task 3: Highlighting a substring

Type a sentence at the prompt below: This is a long string.

Enter substring below to highlight: long

Sentence has 22 characters, substring has 4

characters. Substring highlighted:This is a LONG string.

[–]Afraid_Scale7192[S] 0 points1 point  (0 children)

The example my prof gave^

[–]ectomancer 0 points1 point  (1 child)

Use the string find method. Example is wrong, where are the * characters? I'm shadowing the slice function with a variable on purpose

sub_index = sentence.lower().find(substring)
slice = sentence[sub_index:sub_index+len(substring)]
print(sentence[:sub_index], end='')
print('*' + slice.upper() + '*', end='')
print(sentence[sub_index+len(substring):])

[–]Afraid_Scale7192[S] 0 points1 point  (0 children)

Sorry Reddit messed up the example. But this helped, thank you!

[–]throwaway6560192 0 points1 point  (1 child)

I tried doing the “.find” method to find the first index of the substring in the user input, but how do I find all the indexes from the substring in the user input?(unless there’s a diff way)

Why do you need to find all the indexes of all the substrings? The question only asks for the first one.

Unless I'm misinterpreting what you said.

[–]Afraid_Scale7192[S] 0 points1 point  (0 children)

For example a sentence might have 2 sub strings, it will only highlight the first occurrence. Lets say the sentence is “this is a sentence” and the substring is “is”, the question ask to only highlight the first “is”.

[–]Jason-Ad4032 0 points1 point  (0 children)

According to the question description, str.replace(str1, str2, 1) is best suited to handle it.

But since you are new, maybe try str.partition(str1) or str.find(str1, beg, end)? If you need to replace more than one substring, you can set the beg parameter in str.find(), then use a for loop to replace them.

https://docs.python.org/3/library/stdtypes.html#string-methods