Python 如何将字符串的第一个字符小写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3840843/
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
How to downcase the first character of a string?
提问by Natim
There is a function to capitalize a string, I would like to be able to change the first character of a string to be sure it will be lowercase.
有一个函数可以将字符串大写,我希望能够更改字符串的第一个字符以确保它是小写的。
How can I do that in Python?
我怎样才能在 Python 中做到这一点?
采纳答案by martineau
One-liner which handles empty strings and None:
单行处理空字符串和None:
func = lambda s: s[:1].lower() + s[1:] if s else ''
>>> func(None)
>>> ''
>>> func('')
>>> ''
>>> func('MARTINEAU')
>>> 'mARTINEAU'
回答by RichieHindle
def first_lower(s):
if len(s) == 0:
return s
else:
return s[0].lower() + s[1:]
print first_lower("HELLO") # Prints "hELLO"
print first_lower("") # Doesn't crash :-)
回答by Manoj Govindan
Simplest way:
最简单的方法:
>>> mystring = 'ABCDE'
>>> mystring[0].lower() + mystring[1:]
'aBCDE'
>>>
Update
更新
See this answer(by @RichieHindle) for a more foolproof solution, including handling empty strings. That answer doesn't handle Nonethough, so here is my take:
请参阅此答案(由 @RichieHindle 提供)以获得更万无一失的解决方案,包括处理空字符串。None不过,该答案无法解决,所以这是我的看法:
>>> def first_lower(s):
if not s: # Added to handle case where s == None
return
else:
return s[0].lower() + s[1:]
>>> first_lower(None)
>>> first_lower("HELLO")
'hELLO'
>>> first_lower("")
>>>
回答by JoshD
s = "Bobby tables"
s = s[0].lower() + s[1:]
回答by Adrian McCarthy
Interestingly, none of these answers does exactlythe opposite of capitalize(). For example, capitalize('abC')returns Abcrather than AbC. If you want the opposite of capitalize(), you need something like:
有趣的是,这些答案中没有一个与完全相反capitalize()。例如,capitalize('abC')返回Abc而不是AbC。如果你想要相反的capitalize(),你需要这样的东西:
def uncapitalize(s):
if len(s) > 0:
s = s[0].lower() + s[1:].upper()
return s
回答by Robert Rossney
I'd write it this way:
我会这样写:
def first_lower(s):
if s == "":
return s
return s[0].lower() + s[1:]
This has the (relative) merit that it will throw an error if you inadvertently pass it something that isn't a string, like Noneor an empty list.
这有一个(相对)优点,如果您不经意地传递给它一些不是字符串的东西,比如None或者一个空列表,它会抛出一个错误。
回答by Don O'Donnell
No need to handle special cases (and I think the symmetry is more Pythonic):
无需处理特殊情况(我认为对称性更像 Pythonic):
def uncapitalize(s):
return s[:1].lower() + s[1:].upper()
回答by Van Peer
This duplicate postlead me here.
这个重复的帖子把我带到了这里。
If you've a list of strings like the one shown below
如果您有如下所示的字符串列表
l = ['SentMessage', 'DeliverySucceeded', 'DeliveryFailed']
Then, to convert the first letter of all items in the list, you can use
然后,要转换列表中所有项目的第一个字母,您可以使用
l = [x[0].lower() + x[1:] for x in l]
Output
输出
['sentMessage', 'deliverySucceeded', 'deliveryFailed']

