python capitalize first letter only
Asked Answered
A

10

225

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
Audacity answered 13/9, 2012 at 15:54 Comment(0)
R
258

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'
Rosado answered 13/9, 2012 at 15:56 Comment(9)
I am asking how to capitalize the first alpha characterAudacity
and that is what this answer does, pretty muchJag
I would use if c.isalpha() rather than if not c.isdigit()Jag
Raises exception in case s is empty :)Puttier
@Jan-PhilipGehrcke that is an exercise for the reader. You can see in that case, s is never empty, it is always '123sa' :DRosado
i you can get also via next(i for i,e in enumerate(test) if not e.isdigit()). Which for sure is not nicer than the explicit for loop. Just tried to figure out how it would work using a generator comprehension :)Puttier
@Jan-PhilipGehrcke: in which case, next((i for i,e in enumerate(test) if not e.isdigit()), '0') solves it for the empty string caseJag
This works fine but it makes the rest of the string lowercase. This will convert aA to AaKilbride
This answer is not correct. . capitalize will also transform other chars to lower. From official docs: "Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case."Glede
A
300

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.

Air answered 13/9, 2012 at 16:18 Comment(0)
R
258

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'
Rosado answered 13/9, 2012 at 15:56 Comment(9)
I am asking how to capitalize the first alpha characterAudacity
and that is what this answer does, pretty muchJag
I would use if c.isalpha() rather than if not c.isdigit()Jag
Raises exception in case s is empty :)Puttier
@Jan-PhilipGehrcke that is an exercise for the reader. You can see in that case, s is never empty, it is always '123sa' :DRosado
i you can get also via next(i for i,e in enumerate(test) if not e.isdigit()). Which for sure is not nicer than the explicit for loop. Just tried to figure out how it would work using a generator comprehension :)Puttier
@Jan-PhilipGehrcke: in which case, next((i for i,e in enumerate(test) if not e.isdigit()), '0') solves it for the empty string caseJag
This works fine but it makes the rest of the string lowercase. This will convert aA to AaKilbride
This answer is not correct. . capitalize will also transform other chars to lower. From official docs: "Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case."Glede
T
41

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

Thresathresh answered 26/8, 2015 at 17:15 Comment(5)
Very useful, but needs a len(x) == 0 branch.Transmigrate
since python 2.5 the empty case can still be handled on one line: return x[0].upper() + x[1:] if len(x) > 0 else xCatechu
Very useful answer, because capitalize & title first lowercase the whole string and then uppercase only the first letter.Anson
Useful. Just use a[:1].upper() + a[1:], this will take care of the len(X)==0 corner case.Maemaeander
Good job but don't work for this case because this function capitalize only first caracter and le first caracter is digit not text. You need split numeric and digit before use and join result in this case.Pernell
H
22

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

Hamner answered 22/7, 2014 at 21:26 Comment(1)
This is enormously more efficient than the top-voted answerSelectman
C
9

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"
Columbite answered 11/4, 2017 at 13:1 Comment(1)
How to just capitalise the first letter in the first word?Inwrap
P
7

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

Parabolic answered 25/2, 2018 at 10:23 Comment(0)
R
2

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
Riane answered 16/11, 2016 at 11:25 Comment(0)
G
2
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

Grandam answered 9/10, 2020 at 17:36 Comment(0)
B
1

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
Bonanno answered 13/9, 2012 at 16:6 Comment(0)
T
0
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

Tombolo answered 10/2, 2021 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.