How to capitalize first letter in strings that may contain numbers

  • A+

I would like to read through a file and capitalize the first letters in a string using Python, but some of the strings may contain numbers first. Specifically the file might look like this:

"hello world" "11hello world" "66645world hello" 

I would like this to be:

"Hello world" "11Hello world" "66645World hello" 

I have tried the following, but this only capitalizes if the letter is in the first position.

with open('input.txt') as input, open("output.txt", "a") as output:     for line in input:         output.write(line[0:1].upper()+line[1:-1].lower()+"/n") 

Any suggestions? :-)


You can use regular expression to find the position of the first alphabet and then use upper() on that index to capitalize that character. Something like this should work:

import re  s =  "66645hello world" m ='[a-zA-Z]', s) index = m.start() 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: