转换字符串,使第一个字母为大写,其余的都是小写

2024-05-15 20:40:03 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
How to capitalize the first letter of each word in a string (Python)?

有没有一个选项可以转换一个字符串,使第一个字母是大写的,其他的都是小写的….如下..我知道有大写和小写的转换。。。。

string.upper() //for uppercase 
string.lower() //for lowercase
 string.lower() //for lowercase

INPUT:-italic,ITALIC

OUTPUT:-Italic

http://docs.python.org/2/library/stdtypes.html


Tags: ofthetoforstringlowerhowfirst
3条回答

只需使用str.title()

In [73]: a, b = "italic","ITALIC"

In [74]: a.title(), b.title()
Out[74]: ('Italic', 'Italic')

关于str.title()的帮助:

S.title() -> string

Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.

是的,只需使用capital()方法。

例如:

x = "hello"
x.capitalize()
print x   #prints Hello

Title实际上会将每个单词大写,就像它是一个Title一样。大写将只大写字符串中的第一个字母。

一个简单的方法:

my_string = 'italic'
newstr = my_string[0]
newstr = newstr.upper()
my_string = newstr + my_string[1:]

使其小写(第一个字母除外):

my_string= 'ITALIC'
newstr = my_string[1:]
newstr = newstr.lower()
my_string = my_string[0] + newstr

我不知道是否有一个内置的来做这件事,但这应该是可行的。

相关问题 更多 >