Search code examples
pythonfor-loopif-statementstr-replacecapitalize

How to replace a code not by capitalizing the other ones?


sentence = str ( input ( "Enter a sentence:" ) )
sentence = sentence.split ( )

new = ""
for word in sentence:
    wordi = ord ( word[ 0 ] )
    cap = word[ 0 ]
    a = chr ( (ord ( cap ) - 32) )
    word1 = word.replace ( word[ 0 ] ,a )

    if wordi <= 122 and wordi >= 97:
        new = new + word1 + " "
    else:
        new = new + word + " "

print ( new )

I have been writing about a code that would capitalize all the first letter in the sentence without using the capitalize or upper function. The code that I wrote did appear to be alright when the letter in the word is not the same as the letter that I want to capitalize.

The input:

Hello world

The output:

Hello World

However, if the letter in the word is also the same as the letter that I want to capitalize, the letter within the word will also become capitalized.

The input:

helloh worldw

The output:

HelloH WorldW

I tried to switch the "a" variable inside the replacement and add a to new as well in the variable new in the if-else statement.

sentence = str ( input ( "Enter a sentence:" ) )
sentence = sentence.split ( )

new = ""
for word in sentence:
    wordi = ord ( word[ 0 ] )
    cap = word[ 0 ]
    a = chr ( (ord ( cap ) - 32) )
    word1 = word.replace ( word[ 0 ] ,"" )

    if wordi <= 122 and wordi >= 97:
        new = new + a + word1 + " "
    else:
        new = new + word + " "

print ( new )

But, the code turned out to be that the letter that is being repeated in the word will be deleted when printed.

The input:

helloh 

The output:

Hello

How will I be able to make the code work?


Solution

  • def capitalize(lower_case_word):
        return ' '.join(x[:1].upper() + x[1:] for x in lower_case_word.split())
    
    print(capitalize('hello I am nobody'))
    

    To capitalize all the first characters, this is the one with the best efficiency (by lines).

    def capitalize(lower_case_word):
        lower_case_word = lower_case_word.split()
        new_phrase = ""
    
        for character in lower_case_word:
            new_phrase += character[0].upper() + character[1:] + ' '
    
        return new_phrase
    
    print(capitalize('hello I am nobody'))
    

    This one also works, but it takes several more lines to finish coding. Personally, I recommend the second method if you are a beginner, it is a lot easier to understand since I am also one.