Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My function cannot capitalize the first letter correctly, but I do have "upper" in my code

I want to write a program that takes a sentence as input and then I want to capitalize the first letter of each word in the sentence. Here’s what I have:

input_sentence = input("Enter a sentence: ")
words = input_sentence.split()
for word in words:
    edited_word = word[0].upper() + word[1:]
print("Edited sentence:", ' '.join(words))

When I run this code, it doesn’t seem to change the sentence at all. But I do have upper(). What’s the problem?

I tried to enter a sentence, but the sentence didn’t been capitalized:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter a sentence: i am writing a sentence
Edited sentence: i am writing a sentence

The required output is like:

Enter a sentence: i am writing a sentence
Edited sentence: I Am Writing A Sentence

>Solution :

It seems like you are trying to imitate some sort of textbook code. The problem is that in your loop, you are doing work on edited_word, but use join(words) afterward. You should either rewrite the words or create a new array. Like, don’t expect things to change automatically.

Try this:

words = input("Enter a sentence: ").split()
edited_words = []
for word in words:
    word = word[0].upper() + word[1:]
    edited_words.append(word)
print("Edited sentence:", ' '.join(edited_words))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading