0

I'm trying to write a code that makes the first letter of every line in uppercase, but it is unable to execute past the 6th line if l[0].islower(): . The l[0] works fine when it's outside the loop, but is always says "String Index out of range" when I put it back in the loop.

m = open(r"C:\Users\■■■■■■\Desktop\■■■■\other.txt","r", encoding = "utf-8") #Just blocking the text out

while True:
    l = m.readline()

    if l[0].islower():
        l.replace(l[0],l[0].upper())
        
    print(l)
    
    if not l:
        break
m.close()
3
  • Please share the contents of the input file too. Commented Aug 27, 2020 at 9:36
  • Why are you looping that way? Why not just for line in m? Anyway you should put the if not l right after reading l, not in the end Commented Aug 27, 2020 at 9:45
  • Also, doing replace(l[0], ...) will replace all occurrences of that letter, not just the first Commented Aug 27, 2020 at 9:49

3 Answers 3

1

See capitalize(), its probably what you want.

Also you can iterate a file line by line much easier.

path = r"other.txt"
with open(path, 'r') as file:
    for line in file:
        print(line.capitalize())
Sign up to request clarification or add additional context in comments.

Comments

0

Put the check at the beginning of the loop rather than the end because you go on to access l[0] even if l is None.

while True:

    l = m.readline()
    if not l:
        break

    if l[0].islower():
        l.replace(l[0],l[0].upper())
        
    print(l)
    
m.close()

Comments

0
with open("content.txt", 'r') as file:

    while 1:
        content = file.readline()
        if not content:
            break

        print(content.capitalize())

print("Done !")

you can use this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.