Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize first letter in strings that may contain numbers

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? :-)

like image 359
Dino Avatar asked Nov 01 '18 10:11

Dino


Video Answer


3 Answers

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:])
like image 141
jacob Avatar answered Oct 12 '22 00:10

jacob


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()
like image 3
Ankit Jaiswal Avatar answered Oct 11 '22 23:10

Ankit Jaiswal


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']
like image 3
jpp Avatar answered Oct 11 '22 23:10

jpp