如何将每个单词大写,包括引号开头?

时间:2019-05-31 23:50:54

标签: python

例如,这句话:

say "mosquito!"
 

我尝试使用以下代码大写:

'say "mosquito!"'.capitalize()

哪个返回此:

'Say "mosquito!"’

但是,期望的结果是:

'Say "Mosquito!"’

3 个答案:

答案 0 :(得分:5)

您可以使用str.title

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

# Output: Say "Mosquito!"

看起来Python对此具有内置方法!

答案 1 :(得分:1)

这很棘手。我将寻找单词的第一个字母(字母)。将字符串拆分为单词,然后在将每个单词的首字母转换为大写字母之后再次加入它们。

public class SomeClass
{
    public float KillPosX { get; set; }
    public float KillPosY { get; set; }
    public float KillPosT { get; set; }

    // Values are based on the related property values and cannot be set directly
    public bool KillX => !IsRoughlyZero(KillPosX);
    public bool KillY => !IsRoughlyZero(KillPosY);
    public bool KillT => !IsRoughlyZero(KillPosT);

    private static bool IsRoughlyZero(float input)
    {
        // Use a tolerance for comparing floating point numbers to 0
        return Math.Abs(input) < .0000001;
    }
}

结果:

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

答案 2 :(得分:0)

您可以使用lambda进行正则表达式替换:

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

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

# 'Say "Mosquito\'s House" '