Python 如何更改字符串第一个字母的大小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4223923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:49:34  来源:igfitidea点击:

how to change the case of first letter of a string?

pythonstringuppercase

提问by yyyy

s = ['my', 'name']

I want to change the 1st letter of each element in to Upper Case.

我想将每个元素的第一个字母更改为大写。

s = ['My', 'Name']

回答by Frédéric Hamidi

You can use the capitalize()method:

您可以使用大写()方法:

s = ['my', 'name']
s = [item.capitalize() for item in s]
print s  # print(s) in Python 3

This will print:

这将打印:

['My', 'Name']

回答by Frank

You can use 'my'.title()which will return 'My'.

您可以使用'my'.title()which 将返回'My'

To get over the complete list, simply map over it like this:

要查看完整列表,只需像这样映射它:

>>> map(lambda x: x.title(), s)
['My', 'Name']

Actually, .title()makes all words start with uppercase. If you want to strictly limit it the first letter, use capitalize()instead. (This makes a difference for example in 'this word' being changed to either This Wordor This word)

实际上,.title()使所有单词都以大写开头。如果您想严格限制它的第一个字母,请capitalize()改用。(这会有所不同,例如将“这个词”更改为“This Word或” This word

回答by Kracekumar

You can use

您可以使用

for i in range(len(s)):
   s[i]=s[i].capitalize()
print s

回答by martineau

It probably doesn't matter, but you might want to use this instead of the capitalize()or title()string methods because, in addition to uppercasing the first letter, they also lowercase the rest of the string (and this doesn't):

这可能无关紧要,但您可能想要使用 this 而不是capitalize()title()string 方法,因为除了大写第一个字母之外,它们还会小写字符串的其余部分(而这不是):

s = map(lambda e: e[:1].upper() + e[1:] if e else '', s)

Note:In Python 3, you'd need to use:

注意:在 Python 3 中,您需要使用:

s = list(map(lambda e: e[:1].upper() + e[1:] if e else '', s))

because map()returns an iterator that applies function to every item of iterable instead of a listas it did in Python 2 (so you have to turn it into one yourself).

因为map()返回一个迭代器,该迭代器将 function 应用于 iterable 的每个项目,而不是list像在 Python 2 中所做的那样(所以你必须自己把它变成一个)。

回答by Per Mejdal Rasmussen

Both .capitalize() and .title(), changes the other letters in the string to lower case.

.capitalize() 和 .title() 都将字符串中的其他字母更改为小写。

Here is a simple function that only changes the first letter to upper case, and leaves the rest unchanged.

这是一个简单的函数,它只将第一个字母改为大写,其余保持不变。

def upcase_first_letter(s):
    return s[0].upper() + s[1:]