简体   繁体   English

python只将第一个字母大写

[英]python capitalize first letter only

I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer?我知道 .capitalize() 将字符串的第一个字母大写,但是如果第一个字符是整数呢?

this

1bob
5sandy

to this对此

1Bob
5Sandy

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'

ie 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.但是然后.capitalize()有同样的问题,至少在那个'joe Bob'.capitalize() == 'Joe bob' ,所以meh。

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.如果你想要这个功能, '2'.isdigit()数字,你可以使用'2'.isdigit()来检查每个字符。

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

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.这类似于@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

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)正如@Xan 指出的那样,该函数可以使用更多的错误检查(例如检查 x 是一个序列 - 但是我省略了边缘情况来说明该技术)

Updated per @normanius comment (thanks!)根据@normanius 评论更新(谢谢!)

Thanks to @GeoStoneMarten in pointing out I didn't answer the question!感谢@GeoStoneMarten 指出我没有回答这个问题! -fixed that - 修正了

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这将导致WordsWithOtherUppercaseLetters

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"

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

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

You can replace the first letter ( preceded by a digit ) of each word using regex:您可以使用正则表达式替换每个单词的第一个字母( preceded by a digit ):

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

output:
 1Bob 5Sandy
def solve(s):
    for i in s[:].split():
        s = s.replace(i, i.capitalize())
    return s

This is the actual code for work.这是工作的实际代码。 .title() will not work at '12name' case .title() 在 '12name' 情况下不起作用

def solve(s):

names = list(s.split(" "))
return " ".join([i.capitalize() for i in names])

Takes a input like your name: john doe像你的名字一样输入:john doe

Returns the first letter capitalized.(if first character is a number, then no capitalization occurs)返回大写的第一个字母。(如果第一个字符是数字,则不发生大写)

works for any name length适用于任何名称长度

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

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