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

发布于 2024-10-03 11:51:29 字数 116 浏览 0 评论 0原文

s = ['my', 'name']

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

s = ['My', 'Name']
s = ['my', 'name']

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

s = ['My', 'Name']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

决绝 2024-10-10 11:51:29

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

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

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

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

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:]
无声静候 2024-10-10 11:51:29

您可以使用 capitalize() 方法:

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

这将打印:

['My', 'Name']

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']
可可 2024-10-10 11:51:29

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

要获得完整的列表,只需像这样映射它:

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

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

You can use 'my'.title() which will return '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 Word or This word)

泪眸﹌ 2024-10-10 11:51:29

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

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

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

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

因为 map() 返回一个迭代器它将函数应用于可迭代的每一项,而不是像 Python 2 中那样将函数应用于列表(因此您必须自己将其转换为列表)。

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):

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

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

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 list as it did in Python 2 (so you have to turn it into one yourself).

请叫√我孤独 2024-10-10 11:51:29

您可以使用

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

You can use

for i in range(len(s)):
   s[i]=s[i].capitalize()
print s
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文