IT

파이썬은 첫 글자 만 대문자

lottoking 2020. 6. 3. 08:13
반응형

파이썬은 첫 글자 만 대문자


.capitalize ()가 문자열의 첫 문자를 대문자로 인식하지만 첫 문자가 정수이면 어떻게됩니까?

1bob
5sandy

이에

1Bob
5Sandy

첫 번째 문자가 정수이면 첫 번째 문자를 대문자로하지 않습니다.

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

기능을 원하면 숫자를 제거하고 '2'.isdigit()각 문자를 확인 하는 사용할 수 있습니다 .

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

다른 사람이 언급하지 않았기 때문에 :

>>> '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'있습니다.


이것은 @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)

Updated per @normanius comment (thanks!)

Thanks to @GeoStoneMarten in pointing out I didn't answer the question! -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


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"

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:

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

output:
 1Bob 5Sandy

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

참고URL : https://stackoverflow.com/questions/12410242/python-capitalize-first-letter-only

반응형