繁体   English   中英

在python中将字符串的第一个字母更改为大写

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

我的目标是在输入名称后将专有名词转换为大写的第一个字母。

使用string.title()可以实现:

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

使用upper()方法,像这样:

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

.capitalize() 和 .title() 可以使用,但都有问题:

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

两者都将字符串的其他字母更改为小写。 自己写:

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

您可以使用https://pydash.readthedocs.io/en/latest/api.html#pydash.strings.capitalize

安装pydash - pip install pydash

例子:

from pydash import py_

greetings = "hello Abdullah"

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM