r/PythonLearning • • Sep 10 '25

Making a word in a sentence capital

Post image

im having trouble with syntax to get that selected word in upper case

56 Upvotes

13 comments sorted by

8

u/FirstStatistician133 Sep 10 '25

tweak the body of the function : return sentence.replace(word, word.upper())

5

u/Darknety Sep 11 '25

This is wrong, is => ThIS IS wrong

What you would really need is to split at each whitespace, then replace exact matches of elements stripped of non-alpha-characters.

That is probably more confusing tho.

1

u/FirstStatistician133 Sep 11 '25

Ah, yes. We could probably change mine to sentence.replace(“ “+word+” “,word.upper()) Haha

1

u/Darknety Sep 11 '25

Then case 2 fails.

3

u/FirstStatistician133 Sep 11 '25

def highlight_word(sentence, word):

words = sentence.split()

for i in range(len(words)):

    if words[i].lower() == word.lower():

        words[i] = words[i].upper()

return " ".join(words)

print(highlight_word("This is an error", "is"))

2

u/bananalover2000 Sep 10 '25

Your program is wrong, but what you are trying to do is a bit challenging if you're new to python. Judging from the program you have written, I assume you're not that familiar with strings and touples, so (if I were you) I would look up and familiarise myself with the common object types of python.

I would advise you look at simpler problems first, and later come back to this. Good luck.

1

u/Kqyxzoj Sep 11 '25

hint:

"NICE".lower() is .... ???

So what do we replace? Exactly!

"How nice.".replace("NICE".lower(), "NICE")

And the other way around obviously, you get the idea. ;)

0

u/kjrusse Sep 10 '25

You could try something like this:

import re

def highlight_word(sentence,word):

  return re.sub(word,word.upper(),sentence)

print(highlight_word("Have a nice day","nice"))

1

u/[deleted] Sep 11 '25 edited Sep 11 '25

[removed] — view removed comment

1

u/BluesFiend Sep 11 '25
def highlight_word(sentence, word):
    return " ".join([w.replace(word, word.upper()) for w in sentence.split(" ")])

covers the test cases while keeping it simple.

1

u/[deleted] Sep 11 '25

[removed] — view removed comment

1

u/BluesFiend Sep 11 '25

Good point. I see the flaw again now.