简体   繁体   English

大写一个字符串

[英]Capitalize a string

Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string? 有没有人知道一个非常简单的方法,只是字符串的第一个字母大写,不管其余字符串的大小写?

For example: 例如:

asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest

I would like to be able to do all string lengths as well. 我希望能够完成所有字符串长度。

>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'

@ saua is right, and @ saua是对的,而且

s = s[:1].upper() + s[1:]

will work for any string. 将适用于任何字符串。

What about your_string.title() ? your_string.title()怎么样?

eg "banana".title() -> Banana 例如"banana".title() -> Banana

s = s[0].upper() + s[1:]

除了空字符串(当s="" )时,这应该适用于每个字符串。

this actually gives you a capitalized word, instead of just capitalizing the first letter 这实际上给你一个大写的单词,而不是只是大写第一个字母

cApItAlIzE -> Capitalize cApItAlIzE - >资本化

def capitalize(str): 
    return str[:1].upper() + str[1:].lower().......

for capitalize first word; 为首字母大写;

a="asimpletest"
print a.capitalize()

for make all the string uppercase use the following tip; for make all字符串大写使用以下提示;

print a.upper()

this is the easy one i think. 这是我认为很容易的。

You can use the str.capitalize() function to do that 您可以使用str.capitalize()函数来执行此操作

In [1]: x = "hello"

In [2]: x.capitalize()
Out[2]: 'Hello'

Hope it helps. 希望能帮助到你。

Docs can be found here for string functions https://docs.python.org/2.6/library/string.html#string-functions 可以在这里找到有关字符串函数的文档https://docs.python.org/2.6/library/string.html#string-functions
Below code capitializes first letter with space as a separtor 下面的代码将带有空格的第一个字母作为separtor

s="gf12 23sadasd"
print( string.capwords(s, ' ') )

Gf12 23sadasd Gf12 23sadasd

str = str[:].upper()

在我看来,这是最简单的方法

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

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