nvrthles
nvrthles

Reputation: 99

Changing the first letter of a string into upper case in python

I aim to convert a proper noun for instance to have an upper case first letter after an input of the name has been made.

Upvotes: 3

Views: 13728

Answers (4)

gsamaras
gsamaras

Reputation: 73444

Use upper() method, like this:

mystr = "hello world"
mystr = mystr[0].upper() + mystr[1:]

Upvotes: 10

jcas
jcas

Reputation: 1

You can use https://pydash.readthedocs.io/en/latest/api.html#pydash.strings.capitalize.

Install pydash - pip install pydash

example:

from pydash import py_

greetings = "hello Abdullah"

py_.capitalize(greetings)                  # returns 'Hello abdullah'
py_.capitalize(greetings, strict = False)  # returns 'Hello Abdullah'

Upvotes: 0

PradyJord
PradyJord

Reputation: 2160

.capitalize() and .title(), can be used, but both have issues:

>>> "onE".capitalize()
'One'
>>> "onE".title()
'One'

Both changes other letters of the string to smallcase. Write your own:

>>> xzy = lambda x: x[0].upper() + x[1:]
>>> xzy('onE')
'OnE'

Upvotes: 3

Chen A.
Chen A.

Reputation: 11338

Using string.title() you achieve that:

>>> name = 'joe'
>>> name.title()
'Joe'

Upvotes: 10

Related Questions