-1

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:

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
Leon
  • 1
  • 1
  • 4
    You aren't doing anything with `edited_word`. – mkrieger1 Aug 30 '23 at 21:40
  • `edited_word` is a new object. It's not automatically magically causing the value of `word` to change, nor is it automatically magically changing `input_sentence`. Generally, don't expect things to change automatically and magically; you usually have to make the changes yourself, unless a variable shares a reference with the actual value you want to change. – Random Davis Aug 30 '23 at 21:42
  • The issue with your approach is that simply repeatedly computing a new `edited_word` **has no effect on** the original `word`s in the `words` list. (It's not possible to address this by assigning back to the `word` variable, either, because it is **not a "reference"** for elements of the list.) To fix that general approach, it is necessary to "collect" the results of the transformation into a new list. Alternately, since the goal is to **title-case the sentence**, it would be better to use the built-in functionality that does that directly. I gave you a duplicate link for both approaches. – Karl Knechtel Aug 30 '23 at 21:51

1 Answers1

0

Simple, title() method returns a title cased version of the string.

input_sentence = input("Enter a sentence: ")
print("Edited sentence:", input_sentence.title())