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? :-)
Using regular expressions:
for line in output:
m = re.search('[a-zA-Z]', line);
if m is not None:
index = m.start()
output.write(line[0:index] + line[index].upper() + line[index + 1:])
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 = re.search(r'[a-zA-Z]', s)
index = m.start()
You can write a function with a for
loop:
x = "hello world"
y = "11hello world"
z = "66645world hello"
def capper(mystr):
for idx, i in enumerate(mystr):
if not i.isdigit(): # or if i.isalpha()
return ''.join(mystr[:idx] + mystr[idx:].capitalize())
return mystr
print(list(map(capper, (x, y, z))))
['Hello world', '11Hello world', '66645World hello']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With