Search code examples
pythonstringtranslatecapitalizesentence

Python 3 - How to capitalize first letter of every sentence when translating from morse code


I am trying to translate morse code into words and sentences and it all works fine... except for one thing. My entire output is lowercased and I want to be able to capitalize every first letter of every sentence.

This is my current code:

 text = input()
        if is_morse(text):
            lst = text.split(" ")
            text = ""
            for e in lst:
                text += TO_TEXT[e].lower()
            print(text)

Each element in the split list is equal to a character (but in morse) NOT a WORD. 'TO_TEXT' is a dictionary. Does anyone have a easy solution to this? I am a beginner in programming and Python btw, so I might not understand some solutions...


Solution

  • Maintain a flag telling you whether or not this is the first letter of a new sentence. Use that to decide whether the letter should be upper-case.

    text = input()
    if is_morse(text):
        lst = text.split(" ")
        text = ""
        first_letter = True
        for e in lst:
            if first_letter:
                this_letter = TO_TEXT[e].upper()
            else:
                this_letter = TO_TEXT[e].lower()
    
            # Period heralds a new sentence. 
            first_letter = this_letter == "."  
    
            text += this_letter
        print(text)