问题:python仅将首字母大写

我知道.capitalize()将字符串的第一个字母大写,但是如果第一个字符是整数怎么办?

这个

1bob
5sandy

对此

1Bob
5Sandy

I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer?

this

1bob
5sandy

to this

1Bob
5Sandy

回答 0

如果第一个字符是整数,则不会大写第一个字母。

>>> '2s'.capitalize()
'2s'

如果需要此功能,请去除数字,然后使用'2'.isdigit()来检查每个字符。

>>> s = '123sa'
>>> for i, c in enumerate(s):
...     if not c.isdigit():
...         break
... 
>>> s[:i] + s[i:].capitalize()
'123Sa'

If the first character is an integer, it will not capitalize the first letter.

>>> '2s'.capitalize()
'2s'

If you want the functionality, strip off the digits, you can use '2'.isdigit() to check for each character.

>>> s = '123sa'
>>> for i, c in enumerate(s):
...     if not c.isdigit():
...         break
... 
>>> s[:i] + s[i:].capitalize()
'123Sa'

回答 1

只是因为没有人提到它:

>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'

但是,这也会给

>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'

即,它不只是将第一个字母大写。但是然后.capitalize()有同样的问题,至少在那个'joe Bob'.capitalize() == 'Joe bob'方面如此。

Only because no one else has mentioned it:

>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'

However, this would also give

>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'

i.e. it doesn’t just capitalize the first alphabetic character. But then .capitalize() has the same issue, at least in that 'joe Bob'.capitalize() == 'Joe bob', so meh.


回答 2

这与@Anon的答案类似,因为它使字符串的其余大小写保持不变,而无需re模块。

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

正如@Xan所指出的,该函数可以使用更多的错误检查(例如检查x是否为序列-但是我省略了一些边缘情况来说明该技术)

根据@normanius评论更新(谢谢!)

感谢@GeoStoneMarten指出我没有回答问题!-固定

This is similar to @Anon’s answer in that it keeps the rest of the string’s case intact, without the need for the re module.

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

As @Xan pointed out, the function could use more error checking (such as checking that x is a sequence – however I’m omitting edge cases to illustrate the technique)

Updated per @normanius comment (thanks!)

Thanks to @GeoStoneMarten in pointing out I didn’t answer the question! -fixed that


回答 3

这是一个单行代码,它将大写第一个字母并保留所有后续字母的大小写:

import re

key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key

这将导致 WordsWithOtherUppercaseLetters

Here is a one-liner that will uppercase the first letter and leave the case of all subsequent letters:

import re

key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key

This will result in WordsWithOtherUppercaseLetters


回答 4

正如陈厚武在这里回答的那样,可以使用字符串包:

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"

As seeing here answered by Chen Houwu, it’s possible to use string package:

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"

回答 5

我想出了这个:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

I came up with this:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

回答 6

您可以preceded by a digit使用正则表达式替换每个单词的第一个字母():

re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')

output:
 1Bob 5Sandy

You can replace the first letter (preceded by a digit) of each word using regex:

re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')

output:
 1Bob 5Sandy

回答 7

单线: ' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))

a one-liner: ' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。