torogitar
torogitar

Reputation: 23

How do I make a single letter in a string uppercase

I am trying to take an input text file and make every "i" that is by itself uppercase. This is my code so far, but it creates one long line of code instead of keeping the line breaks and paragraphs.

with open("greenEggsAndHam.txt", "r") as myfile:
    iText = myfile.read().split()

oText = ''

for word in iText:
    if(word == "i"):
        word = word.upper()
    oText = oText + word + " "
print oText

the output is now like this:

I am Sam Sam I am That Sam-i-am!That Sam-i-am! I do not like that Sam-i-am!

instead of this:

I am Sam
Sam I am

That Sam-i-am!
That Sam-i-am!
I do not like that Sam-i-am!

is there a way to do this while keeping paragraphs and line breaks?

Upvotes: 1

Views: 103

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180512

Your code fails as you split the text into one large list of individual words so any newlines are removed, that is why you are left with one large line of text.

You can split each line as you iterate over the file object and check for i:

with open("greenEggsAndHam.txt", "r") as myfile:
   for line in myfile:
       print(" ".join([w.upper() if w == "i" else w for w in line.split()]))

If you want one large body of text:

with open("greenEggsAndHam.txt", "r") as myfile:
   text = "\n".join([" ".join([ch.upper() if ch == "i" else ch for ch in line.split()]) for line in myfi

Upvotes: 2

Alex Hall
Alex Hall

Reputation: 36043

import re
string = re.sub('\bi\b', 'I', string)

Upvotes: 1

Related Questions