[英]How to capitalize the First letter of each word in python?
You are asked to ensure that the first and last names of people begin with a capital letter in their passports.您需要确保护照上的人的名字和姓氏以大写字母开头。 For example, alison heck should be capitalised correctly as Alison Heck.
例如,alison heck 应该正确地大写为 Alison Heck。
the code I've tried:我试过的代码:
def solve(s):
words = s.split()
flag = False
for word in words:
if isinstance(word[0], str):
flag = True
else:
flag = False
if flag:
return s.title()
else:
# don't know what to do
s = input()
print(solve(s))
this code works fine for most cases except for one,此代码适用于大多数情况,除了一个,
frustrating testcase: '1 w 2 r 3g', and the output should be '1 W 2 R 3g', but since we are using the.title() method last 'g' will also be capitalized.令人沮丧的测试用例:'1 w 2 r 3g',而 output 应该是'1 W 2 R 3g',但由于我们使用的是 .title() 方法,所以最后一个 'g' 也将大写。
We can try using re.sub
here matching the pattern \b(.)
, along with a callback function which uppercases the single letter being matched.我们可以在这里尝试使用
re.sub
匹配模式\b(.)
,以及一个回调 function ,它将匹配的单个字母大写。
inp = '1 w 2 r 3g'
output = re.sub(r'\b(.)', lambda x: x.group(1).upper(), inp)
print(output) # 1 W 2 R 3g
name = 'robert lewandowski'
print(name.title())
Output - Output -
Robert Lewandowski
Check this if solves your problem如果可以解决您的问题,请检查此
z=[]
s = input()
x=s.split(" ")
print(x)
for i in x:
z.append(i.capitalize())
v=" ".join(z)
print(v)
You can call like:你可以这样打电话:
s = '1 w 2 r 3gH'
print(' '.join([word.capitalize() for word in s.split()]))
# 1 W 2 R 3gh
But note that the remaining letters also will be made in lowercase except the first letter as given in the altered example.但请注意,其余字母也将使用小写字母,除了更改示例中给出的第一个字母。
if you use numpy module, then easily you can achieve the answer!如果您使用 numpy 模块,那么您可以轻松获得答案! for example = Alison Heck
例如 = 艾莉森·赫克
from numpy import *
answer=input("give your input").title()
print(answer)
this module especially made for this purpose.该模块专门为此目的而制作。
You can use RE or you can try a solution like this您可以使用 RE,也可以尝试这样的解决方案
def solve(s):
res=""
for i in range(len(s)):
if i==0:
if s[i].isalpha():
res+=s[i].capitalize()
else:
res+=s[i]
else:
if s[i].isalpha() and s[i-1]==' ':
res+=s[i].capitalize()
else:
res+=s[i]
return res
#replace #代替
def solve(s): def 解决:
for i in s.split():
s = s.replace(i,i.capitalize())
return s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.