Home > Enterprise >  Not getting output new to Python
Not getting output new to Python

Time:03-31

I am new to Python.

How do we write this.

My out put is not correct

My output is incorrect

Programming challenge description:

Write a program which capitalizes the first letter of each word in a sentence.

Input:

Your program should read lines from standard input. Each line has a sequence of words.

Output:

Print the capitalized words.

Test 1

Test InputDownload Test 1 Input

Hello world

Expected OutputDownload Test 1 Input

Hello World

Test 2

Test InputDownload Test 2 Input

a letter

Expected OutputDownload Test 2 Input

A Letter

import sys
# import numpy as np
# import pandas as pd
# from sklearn import ...

for line in sys.stdin:
    print(line, end="")
    line = "Hello world"

CodePudding user response:

To capitalize a word use your_word.capitalize()

If you need to capitalize each word of a sentence like "Hello world!" you first need to split your sentence in a list of word:

sentence = "Hello world!"
words = sentence.split(" ")

Then, Modify the list capitalizing each word.

words = [word.capitalize() for word in words]

And finally convert you list back to a string to get the wanted result

result = " ".join(words)

For the 2nd example if you just need to capitalize the first word, instead of using the list comprehension words = [word.capitalize() for word in words] you can just mutate the first element of the list, without reassigning it entirely

words[0] = words[0].capitalize()

Here is a concrete example using input

def capitalizeSentence(s):
    return " ".join([w.capitalize() for w in s.split(" ")])

inputSentence = input("type a sentence")
print(capitalizeSentence(inputSentence))

CodePudding user response:

This is my version with some comments to help:

# Write a program which capitalizes the first letter of each word in a sentence.


sentance = 'hello and have a nice day'
new_sentance = ''

# split the sentance
words = sentance.split(' ')

# make each first letter uppercase
for word in words:
    new_sentance = new_sentance   ' '   word.capitalize()



print(new_sentance)

result:

Hello And Have A Nice Day
  • Related