python capitalize first letter only

PythonCapitalizeLetter

Python Problem Overview


I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer?

this

1bob
5sandy

to this

1Bob
5Sandy

Python Solutions


Solution 1 - Python

Only because no one else has mentioned it:

>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'

However, this would also give

>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'

i.e. it doesn't just capitalize the first alphabetic character. But then .capitalize() has the same issue, at least in that 'joe Bob'.capitalize() == 'Joe bob', so meh.

Solution 2 - Python

If the first character is an integer, it will not capitalize the first letter.

>>> '2s'.capitalize()
'2s'

If you want the functionality, strip off the digits, you can use '2'.isdigit() to check for each character.

>>> s = '123sa'
>>> for i, c in enumerate(s):
...     if not c.isdigit():
...         break
... 
>>> s[:i] + s[i:].capitalize()
'123Sa'

Solution 3 - Python

This is similar to @Anon's answer in that it keeps the rest of the string's case intact, without the need for the re module.

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

As @Xan pointed out, the function could use more error checking (such as checking that x is a sequence - however I'm omitting edge cases to illustrate the technique)

Updated per @normanius comment (thanks!)

Thanks to @GeoStoneMarten in pointing out I didn't answer the question! -fixed that

Solution 4 - Python

Here is a one-liner that will uppercase the first letter and leave the case of all subsequent letters:

import re

key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key

This will result in WordsWithOtherUppercaseLetters

Solution 5 - Python

As seeing here answered by Chen Houwu, it's possible to use string package:

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"

Solution 6 - Python

a one-liner: ' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))

Solution 7 - Python

You can replace the first letter (preceded by a digit) of each word using regex:

re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')

output:
 1Bob 5Sandy

Solution 8 - Python

def solve(s):
    for i in s[:].split():
        s = s.replace(i, i.capitalize())
    return s

This is the actual code for work. .title() will not work at '12name' case

Solution 9 - Python

I came up with this:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

Solution 10 - Python

def solve(s):

names = list(s.split(" "))
return " ".join([i.capitalize() for i in names])

> Takes a input like your name: john doe

> Returns the first letter capitalized.(if first character is a number, then no capitalization occurs)

> works for any name length

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1442957View Question on Stackoverflow
Solution 1 - PythonDSMView Answer on Stackoverflow
Solution 2 - PythonAli AfsharView Answer on Stackoverflow
Solution 3 - PythonpinkwerksView Answer on Stackoverflow
Solution 4 - PythonAnonView Answer on Stackoverflow
Solution 5 - PythonFábioView Answer on Stackoverflow
Solution 6 - PythonGürol CanbekView Answer on Stackoverflow
Solution 7 - PythonKenlyView Answer on Stackoverflow
Solution 8 - Pythonshubhajit22View Answer on Stackoverflow
Solution 9 - PythonPrasanthView Answer on Stackoverflow
Solution 10 - PythonVivek Sivalingam RamanathanView Answer on Stackoverflow