如何将python中每个单词的首字母大写?

How to capitalize the First letter of each word in python?

您需要确保护照上的人名和姓氏以大写字母开头。例如,alison heck 应该正确地大写为 Alison Heck。

我试过的代码:

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))
        

此代码适用于大多数情况,除了一种情况,

令人沮丧的测试用例:'1 w 2 r 3g', 输出应为“1 W 2 R 3g”, 但由于我们使用的是 .title() 方法,最后 'g' 也将被大写。

我们可以尝试在这里使用 re.sub 来匹配模式 \b(.),以及一个将匹配的单个字母大写的回调函数。

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

如果能解决您的问题,请勾选

z=[]
s = input()
x=s.split(" ")
print(x)
for i in x:
    z.append(i.capitalize())

v=" ".join(z)
print(v)

你可以这样打电话:

s = '1 w 2 r 3gH'
print(' '.join([word.capitalize() for word in s.split()]))
# 1 W 2 R 3gh

但请注意,除了第一个字母以外,其余字母也将变为小写,如更改示例中给出的那样。

如果你使用了numpy模块,那么很容易就能得到答案! 例如 = Alison Heck

from numpy import *

answer=input("give your input").title()
print(answer)

这个模块是专门为此目的而制作的。

您可以使用 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 解决:

for i in s.split():
    s = s.replace(i,i.capitalize())
return s

在 Python 中,capitalize() 方法 returns 原始字符串的副本,并将字符串的第一个字符转换为大写(大写)字母,同时使所有其他字符成为字符串小写字母。

name = 'robert lewandowski'
print(name.title())

输出-

Robert Lewandowski