如何大写每个词,包括在一个引语的开头?

2024-04-25 10:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,这句话:

say "mosquito!"

我尝试用以下代码大写:

'say "mosquito!"'.capitalize()

返回以下内容:

'Say "mosquito!"’

然而,期望的结果是:

'Say "Mosquito!"’

Tags: 代码say大写mosquitocapitalize
3条回答

这是相当棘手的。我要找一个单词的第一个字母。将字符串拆分为单词,并在将每个单词的第一个字母转换为大写后再次连接它们。你知道吗

def start(word):
    for n in range(len(word)):
        if word[n].isalpha():
            return n
    return 0

strng = 'say mosquito\'s house'
print( ' '.join(word[:start(word)] + word[start(word)].upper() + word[start(word)+1:] for word in strng.split()))

结果:

Say "Mosquito's House"

您可以使用str.title

print('say "mosquito!"'.title())

# Output: Say "Mosquito!"

看起来Python有一个内置的方法!你知道吗

可以在正则表达式替换中使用lambda:

string = 'say "mosquito\'s house" '  

import re
caps   = re.sub("((^| |\")[a-z])",lambda m:m.group(1).upper(),string)

# 'Say "Mosquito\'s House" '

相关问题 更多 >