파이썬은 첫 글자 만 대문자
.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
'IT' 카테고리의 다른 글
SQL Server Management Studio로 복합 키를 만들려면 어떻게해야합니까? (0) | 2020.06.03 |
---|---|
z-index가 작동하지 않는 이유는 무엇입니까? (0) | 2020.06.03 |
키 / 값 자바 스크립트 객체의 키를 얻는 가장 좋은 방법 (0) | 2020.06.03 |
역사없이 git repo를 복사하십시오. (0) | 2020.06.03 |
“java.net.BindException : 이미 사용중인 주소 : JVM_Bind”오류를 어떻게 해결합니까? (0) | 2020.06.03 |